我有一个带有一些参数的存储过程,其中一个参数是'汽车名称'列表。例如
CALL `car_list_inventory`(1,"'Honda','Nissan','BMW','Toyota'");
存储过程的结果返回当前可用的汽车名称的名称,例如if 我是要运行结果的程序
store cars_available
---- ----------------
1 Honda, BMW
确定可用汽车的部分查询
SELECT store, GROUP_CONCAT(DISTINCT cars.model) AS cars_available
FROM cars
JOIN cars_avail ON cars.id = cars_avail.id_ref
WHERE cars.id = LAST_INSERT_ID();
我想要做的是添加第二部分,它将返回不可用的汽车,例如,整个结果应该看起来像
store cars_available cars_not_available
----- ---------------- ----------------
1 Honda, BMW Nissan, Toyota
这可能吗?
答案 0 :(得分:0)
获取不可用的汽车:
SELECT store, GROUP_CONCAT(DISTINCT cars.model) AS cars_not_available
FROM cars
LEFT JOIN cars_avail ON cars.id = cars_avail.id_ref
WHERE cars_avail.id_ref IS NULL
GROUP BY store
您还可以使用NOT IN
:
SELECT store, GROUP_CONCAT(DISTINCT cars.model) AS cars_not_aveilable
FROM cars
WHERE id NOT IN (SELECT id_ref FROM cars_avail)
GROUP BY store
要在一个查询中获取两者,您可以执行以下操作:
SELECT store,
GROUP_CONCAT(CASE WHEN cars_avail.id_ref IS NOT NULL
THEN cars.model
END) AS cars_available,
GROUP_CONCAT(CASE WHEN cars_avail.id_ref IS NULL
THEN cars.model
END) AS cars_not_available
FROM cars
LEFT JOIN cars_avail ON cars.id = cars_avail.id
GROUP BY store
答案 1 :(得分:0)
您正试图让您的问题适合您已选择的API - 这是找到解决方案的错误方法。特别是当您试图打破关系数据库的基本规则之一时:属性(在这种情况下是过程参数)不应该包含多个值。
使用SQL解决变量参数列表问题的正确方法是将值列表放入表中并进行连接。您可以通过解析单个字符串来分割出值来实现这一目标,但我猜测您不会向用户提供原始的MySQL访问权限 - 因此从的> > 用于桥接访问,然后....
INSERT INTO search (session, model, created)
VALUES
(CONNECTION_ID(), 'Honda', NOW()),
(CONNECTION_ID(), 'Nissan', NOW()),
(CONNECTION_ID(), 'BMW', NOW()),
(CONNECTION_ID(), 'Toyota', NOW());
SELECT store, SUM(IF(cars.model IS NULL, 0, 1)) AS matches,
GROUP_CONCAT(cars.model) AS available,
GROUP_CONCAT(IF(cars.model IS NULL, search.models, NULL)) AS notavailable
FROM search
LEFT JOIN cars
ON search.model=cars.model
AND cars,stock>0
WHERE search.session=CONNECTION_ID()
GROUP by store
ORDER BY matches;
DELETE FROM search
WHERE session=CONNECTION_ID();