我的项目table1
和table2
中有2个表格,并且在两个表格中使用参数id
作为列
id
仅在表1中 ,我会在table1
中找到该行。如果id
仅在表格2中找到,那么我只会在table2
中获得一行。
我尝试使用INNER JOIN
,如果第一个表格不包含id
,即使其他表格中id
它不会选择,我也会尝试{{1}但是,第一个表不包含if的那一刻,即使第二个表有它,我也无法选择。与LEFT JOIN
相同,如果第二个表格没有RIGHT JOIN
我无法选择。
任何想法都是适用的
更新
答案 0 :(得分:2)
您需要UNION
声明
(SELECT * FROM table1 WHERE id = 1)
UNION
(SELECT * FROM table2 WHERE id = 1)
https://dev.mysql.com/doc/refman/5.0/en/union.html
修改强>
如果使用UNION
连接两个表,结果将从第一个表中获取字段名称。
table1
+----+-------+
| id1| text1 |
+----+-------+
| 1 | aaa |
+----+-------+
table2
+----+-------+
| id2| text2 |
+----+-------+
| 1 | bbb |
+----+-------+
(SELECT 't1' AS 'table', id1, text1 FROM table1)
UNION
(SELECT 't2' AS 'table', id2, text2 FROM table2)
Result:
+-------+----+-------+
| table | id1| text1 | <-- field names from the first table in the UNION query
+-------+----+-------+
| t1 | 1 | aaa |
+-------+----+-------+
| t2 | 1 | bbb |
+-------+----+-------+
答案 1 :(得分:1)
您可以使用UNION
,但需要从两个表格中选择相同数量的列:
(SELECT col_y AS the_data FROM table_y WHERE id = :id)
UNION
(SELECT col_x AS the_data FROM table_x WHERE id = :id)
请注意,只绑定一个变量可以工作,但这取决于您的PDO设置。如果它不起作用,则需要绑定2个单独的变量:
(SELECT col_y AS the_data FROM table_y WHERE id = :this_is_your_id)
UNION
(SELECT col_x AS the_data FROM table_x WHERE id = :really_the_same_id)
答案 2 :(得分:0)
http://se2.php.net/manual/en/mysqli.multi-query.php
<?php
$query = "SELECT * FROM table1 WHERE id = 1";
$query .= "SELECT * FROM table2 WHERE id = 1";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
?>