我有两张表complain
和repair
。如果ass_to_per
中不存在repair
complain
,我希望从id
或complain
获取repair
[最新一个]。< / p>
说明:
我想从ass_to_per
表中获取complain
,也从repair
表中获取repair
。但是它们之间存在关系,在com_id
中有一个名为ass_to_per
的字段,它是一个外键。所以我想从complain
获取repair
,并检查ass_to_per
是否有外键,如果有的话,请检查修复的sqlfiddle
。如果有,那么得到它作为结果。
我有CREATE TABLE `complain` (
`id` int(11) NOT NULL,
`ass_to_per` varchar(50) NOT NULL
);
INSERT INTO `complain` (`id`, `ass_to_per`) VALUES
(1, 'frayne'),
(2, 'murad'),
(4, 'frayne'),
(5, 'murad'),
(6, 'frayne'),
(7, 'frayne');
,对于在线测试:sqlfiddle.com
下面给出的表格和数据。
投诉
CREATE TABLE `repair` (
`id` int(11) NOT NULL,
`com_id` int(11) NOT NULL,
`ass_to_per` varchar(50) NOT NULL
);
INSERT INTO `repair` (`id`, `com_id`, `ass_to_per`) VALUES
(1, 1, 'frayne'),
(2, 1, 'murad'),
(3, 4, 'frayne'),
(4, 6, 'murad'),
(5, 2, 'murad'),
(6, 5, 'frayne');
修复
SELECT * FROM `complain`
WHERE `id` IN (SELECT DISTINCT(`com_id`) FROM `repair` WHERE `ass_to_per` = 'frayne') OR `ass_to_per`='frayne'
我的查询:
id | ass_to_per
--------------
1 | frayne
4 | frayne
5 | murad
6 | frayne
7 | frayne
查询结果
id | ass_to_per[complain] | ass_to_per[repair]
--------------
1 | murad | frayne
2 | murad | murad
4 | frayne | frayne //need this one
5 | murad | frayne //need this one
6 | frayne | murad
7 | frayne | //need this one
分析
id | ass_to_per
--------------
4 | frayne //ass_to_per from repair
5 | frayne //ass_to_per from repair
7 | frayne //ass_to_per from complain
预期结果:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
if ($result = mysqli_query($link, "SELECT * FROM City", MYSQLI_USE_RESULT)) {
if (!mysqli_query($link, "SET @a:='this will not work'")) {
printf("Error: %s\n", mysqli_error($link));
}
mysqli_free_result($result);
}
mysqli_close($link);
?>
答案 0 :(得分:1)
COALESCE()
将输出它找到的第一个非null参数,因此使用连接可能会从抱怨或修复中获取ass_to_per,具体取决于存在哪个:
SELECT
complain.id,
COALESCE(repair3.ass_to_per, complain.ass_to_per) as ass_to_per
FROM complain
LEFT JOIN
(SELECT max(id) as maxid, com_id FROM repair GROUP BY com_id) as repair2
ON complain.id = repair2.com_id
LEFT JOIN repair as repair3
ON repair2.maxid = repair3.id
GROUP BY complain.id
如果你想在计算出的ass_to_per上进一步过滤(比如'frayne'中的例子),只需将此选项嵌入子查询:
SELECT *
FROM (
SELECT
complain.id,
COALESCE(repair3.ass_to_per, complain.ass_to_per) as ass_to_per
FROM complain
LEFT JOIN (SELECT max(id) as maxid, com_id FROM repair GROUP BY com_id) AS repair2
ON complain.id = repair2.com_id
LEFT JOIN repair as repair3
ON repair2.maxid = repair3.id
GROUP BY complain.id
) AS mydata
WHERE mydata.ass_to_per = 'frayne'
ORDER BY mydata.id;
答案 1 :(得分:0)
SELECT c.id
FROM complain c
LEFT
JOIN
( SELECT x.*
FROM repair x
JOIN
( SELECT com_id,MAX(id) id FROM repair GROUP BY com_id ) y
ON y.com_id = x.com_id
AND y.id = x.id
) r
ON r.com_id = c.id
WHERE COALESCE(r.ass_to_per,c.ass_to_per) = 'frayne';