数据库
首页 > 数据库> > mysql – 如何在jdbc数据源中使用子查询来获取dbtable选项?

mysql – 如何在jdbc数据源中使用子查询来获取dbtable选项?

作者:互联网

我想使用Spark来处理来自JDBC源的一些数据.但首先,我想在JDBC端运行一些查询来过滤列和连接表,而不是从JDBC读取原始表,而是将查询结果作为表加载到Spark SQL中.

加载原始JDBC表的以下语法适用于我:

df_table1 = sqlContext.read.format('jdbc').options(
    url="jdbc:mysql://foo.com:3306",
    dbtable="mydb.table1",
    user="me",
    password="******",
    driver="com.mysql.jdbc.Driver" # mysql JDBC driver 5.1.41
).load() 
df_table1.show() # succeeded

根据Spark documentation(我正在使用PySpark 1.6.3):

dbtable: The JDBC table that should be read. Note that anything that is valid
in a FROM clause of a SQL query can be used. For example, instead of a
full table you could also use a subquery in parentheses.

所以只是为了实验,我尝试了这样简单的事情:

df_table1 = sqlContext.read.format('jdbc').options(
    url="jdbc:mysql://foo.com:3306",
    dbtable="(SELECT * FROM mydb.table1) AS table1",
    user="me",
    password="******",
    driver="com.mysql.jdbc.Driver"
).load() # failed

它引发了以下异常:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table1 WHERE 1=0' at line 1

我还尝试了一些语法的其他变体(添加/删除括号,删除’as’子句,切换案例等),没有任何运气.那么正确的语法是什么?我在哪里可以找到更详细的语法文档?此外,错误信息中这个奇怪的“WHERE 1 = 0”来自何处?谢谢!

解决方法:

要在Spark SQL中使用sql查询从JDBC源读取数据,可以尝试这样的方法:

val df_table1 = sqlContext.read.format("jdbc").options(Map(
    ("url" -> "jdbc:postgresql://localhost:5432/mydb"),
    ("dbtable" -> "(select * from table1) as table1"),
    ("user" -> "me"),
    ("password" -> "******"),
    ("driver" -> "org.postgresql.Driver"))
).load()

我用PostgreSQL试了一下.你可以根据MySQL修改它.

标签:pyspark-sql,apache-spark,apache-spark-sql,mysql,jdbc
来源: https://codeday.me/bug/20190930/1836983.html