我有一个脚本,经过检查的员工可以看到彼此的库存,与他们的个人库存位置相关联,因此每个签到的员工都可以看到哪些商品在不同地点有库存。但是,我希望始终显示主库存(1
的ID,而不是附加到员工),但我无法正确查询,因为其中一个where
语句显然不正确:
`stock_locations`.`location_id` = 1 AND
`workschedule`.`checkedIn` = 1 AND
记住,主要股票没有与员工挂钩,因此它不会出现在workschedule
表格中。如果我删除了第一个声明,它会清楚地显示所有已检查的员工的位置,但这并不能给我主要的库存。如果我删除第二个语句,它只显示主要股票。
如何在SQL中解决此问题?这是完整的陈述:
SELECT
`item_quantities`.`item_id`,
`stock_locations`.`location_name`,
`item_quantities`.`quantity`,
`people`.`first_name`
FROM
`item_quantities`
JOIN `stock_locations` ON `item_quantities`.`location_id` = `stock_locations`.`location_id`
JOIN `items` ON `item_quantities`.`item_id` = `items`.`item_id`
LEFT JOIN `workschedule` ON `workschedule`.`linked_storage` = `stock_locations`.`location_id`
LEFT JOIN `people` ON `workschedule`.`employee_id` = `people`.`person_id`
WHERE
`stock_locations`.`location_id` = 1 AND
`workschedule`.`checkedIn` = 0 AND
`items`.`unit_price` != 0 AND
`items`.`deleted` = 0 AND
`stock_locations`.`deleted` = 0 NULL
提前致谢!
答案 0 :(得分:2)
在parens里面做一个OR语句。
(`stock_locations`.`location_id` = 1 OR `workschedule`.`checkedIn` = 1) AND
这将返回与主要股票或员工匹配的所有记录。
答案 1 :(得分:1)
您需要使用OR
运算符。显然,这两件事情不可能同时发生,因此您需要指定每组可接受的条件。
SELECT
`item_quantities`.`item_id`,
`stock_locations`.`location_name`,
`item_quantities`.`quantity`,
`people`.`first_name`
FROM
`item_quantities`
JOIN `stock_locations`
ON `item_quantities`.`location_id` = `stock_locations`.`location_id`
JOIN `items`
ON `item_quantities`.`item_id` = `items`.`item_id`
LEFT JOIN `workschedule`
ON `workschedule`.`linked_storage` = `stock_locations`.`location_id`
LEFT JOIN `people`
ON `workschedule`.`employee_id` = `people`.`person_id`
WHERE
`stock_locations`.`location_id` = 1
OR (
AND `workschedule`.`checkedIn` = 1
AND `items`.`unit_price` != 0
AND `items`.`deleted` = 0
AND `stock_locations`.`deleted` = 0
NULL
)
答案 2 :(得分:0)
您有LEFT JOIN
,但您的WHERE
子句将它们转换为内部联接。修复可能会解决您的问题:
SELECT . . .
FROM item_quantities iq JOIN
stock_locations sl
ON iq.`location_id` = sl.`location_id` JOIN
items i
ON iq.`item_id` = i.`item_id` LEFT JOIN
workschedule ws
ON ws.`linked_storage` = sl.`location_id` AND
ws.`checkedIn` = 0 LEFT JOIN
--------^
people p
ON ws.`employee_id` = p.`person_id`
WHERE sl.`location_id` = 1 AND
i.`unit_price` != 0 AND
i.`deleted` = 0 AND
sl.`deleted` = 0