让我澄清一下,我的问题是“如何在不重复值的情况下从绑定(bind)的单个表和交叉引用表中选择行?”
现在我有三个表,一个交叉引用表和两个单表:
Table jobs
╔══════════╦══════════════════════════╗
║ job_id ║ details ║
╠══════════╬══════════════════════════╣
║ 1 ║ Looking for hire... ║
║ 2 ║ We need help!... ║
║ 3 ║ We are a store that... ║
║ 4 ║ Help wanted... ║
╚══════════╩══════════════════════════╝
Table job2pos
╔═══════════╦═════════════╗
║ job_id ║ position_id ║
╠═══════════╬═════════════╣
║ 1 ║ 10 ║
║ 2 ║ 10 ║
║ 2 ║ 12 ║
║ 3 ║ 11 ║
║ 3 ║ 13 ║
║ 4 ║ 10 ║
╚═══════════╩═════════════╝
Table positions
╔═══════════════╦═══════════════╗
║ position_id ║ position_name ║
╠═══════════════╬═══════════════╣
║ 10 ║ waitress ║
║ 11 ║ cashier ║
║ 12 ║ cook ║
║ 13 ║ chef ║
╚═══════════════╩═══════════════╝
当我执行这个查询时:
$sql = "SELECT jobs.details, positions.name AS position FROM jobs
INNER JOIN job2pos ON jobs.job_id = job2pos.job_id
INNER JOIN positions ON job2pos.position_id = positions.position_id
WHERE job2pos.job_id IN (2)";
...
print_r($stmt->fetchAll(\PDO::FETCH_ASSOC));
我得到以下信息:
Array(
[0] => Array ([details] => We need help!...
[position] => Waitress)
[1] => Array ([details] => We need help!...
[position] => Cook)
)
现在同一份工作我得到了 2 行,但我想要的是与此类似的内容:
Array(
[0] => Array ([details] => We need help!...
[position] => Array ([0] => Waitress
[1] => Cook)
)
)
- 如果您能指出我的代码中一些不必要的代码,那就太好了。
最佳答案
您所描述的仅使用一个 sql 语句是不可能的。您可以将结果想象成一张表格。普通 sql 中不能有任何嵌套信息。
我们可以选择 nosql用于存储和检索对象的数据库。
但是,我认为您真正想要的是选择 multiple statements with one call
.
MySQL optionally allows having multiple statements in one statement string. Sending multiple statements at once reduces client-server round trips but requires special handling.
Multiple statements or multi queries must be executed with
mysqli_multi_query()
. The individual statements of the statement string are separated by semicolon. Then, all result sets returned by the executed statements must be fetched.The MySQL server allows having statements that do return result sets and statements that do not return result sets in one multiple statement.
对于来自 this Q&A 的 PDO :
$stmt = $db->query("SELECT 1; SELECT 2;");
$stmt->nextRowset(); //Move to next statement result
var_dump( $stmt->fetchAll(PDO::FETCH_ASSOC) ); //SELCT 2 result
关于php - 从两个表中选择而不重复所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40621203/