4
讓我澄清一下自己,我的問題是「如何從綁定單個表和交叉引用表中選擇行而不重複值?」從兩個表中選擇而不重複所有值
現在我有三個表,交叉引用表和兩個單表:
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)
)
)
- 如果你能指出我的代碼中的一些不必要的代碼,我將是巨大的。
嘗試添加'選擇不同jobs.job_id'? –
您可能必須將查詢分解爲2個單獨的查詢。它的工作方式應該是。 – Maximus2012
@ user3360140嘗試過,但不起作用:< – Sarah