[英]SQL - Get data from 2 tables
I've read other threads about getting queries from 2 tables, but I still don't now how to implement my issue. 我已经阅读了有关从2个表获取查询的其他主题,但是现在我仍然不知道如何实现我的问题。
There is a Feed page where user gets queries from Table A sorted by date. 在供稿页面上,用户可以从表A中获取按日期排序的查询。 And there is another Table B that contains some queries.
还有另一个包含一些查询的表B。 I need to get queries from both tables, mix them, and sort by date.
我需要从两个表中获取查询,将它们混合并按日期排序。
Table A 表A
----id---- ----date---- ----post----
1 20170514 post 1
2 20170512 post 3
3 20170510 post 5
Table B 表B
----id---- ----date---- ----post---- ----thread----
1 20170513 post 2 1
2 20170511 post 4 2
SELECT * FROM tableA WHERE post!="" AND date!=""
and SELECT * FROM tableB WHERE post!="" AND date!=""
SELECT * FROM tableA WHERE post!="" AND date!=""
和SELECT * FROM tableB WHERE post!="" AND date!=""
Output (in plaint text to screen) should be: 输出(以纯文本显示在屏幕上)应为:
You can use UNION like this 您可以像这样使用UNION
SELECT id, date, post FROM TABLEA
WHERE date IS NOT NULL AND
post IS NOT NULL
UNION
SELECT id, date, post FROM TABLEB
WHERE date IS NOT NULL AND
post IS NOT NULL
you may need to use alias for the tables. 您可能需要为表使用别名。
If you'd like to see a result-set containing both tables' rows, you should use JOIN
but in this case, you should be able to connect those two tables. 如果要查看包含两个表的行的结果集,则应使用
JOIN
但在这种情况下,应该能够连接这两个表。 For example if you have a product
table, and a product_details
, then you should have a field on the second table like product_id
which is pointing to an existing product's id. 例如,如果您有一个
product
表和一个product_details
,那么您应该在第二个表上有一个指向product_id
的字段,该字段指向现有产品的ID。 you can find out more here: 在这里你可以找到更多:
https://www.w3schools.com/sql/sql_join.asp https://www.w3schools.com/sql/sql_join.asp
Otherwise you could try UNION
which is used to combine two ore more result-ser of multiple SELECT
statements: 否则,您可以尝试
UNION
,该UNION
用于合并多个SELECT
语句的两个或多个结果服务器:
https://www.w3schools.com/sql/sql_union.asp https://www.w3schools.com/sql/sql_union.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.