我有一个声明我的工作方式,但是它是正确的方式,因为我有很多IF语句,并想知道它是否对性能有影响,或者我应采取不同的方法进行最佳实践。这是从阅读文档创建的,所以我可能已经走了它的日志方式。
SELECT c.id, c.first_name, c.last_name,
IF( c.id IN (SELECT client_id FROM bookings) AND '1' IN (SELECT practitioner_id FROM bookings) , c.address1, NULL) as address1,
IF( c.id IN (SELECT client_id FROM bookings) AND '1' IN (SELECT practitioner_id FROM bookings) , c.address2, NULL) as address2,
IF( c.id IN (SELECT client_id FROM bookings) AND '1' IN (SELECT practitioner_id FROM bookings) , c.town, NULL) as town,
IF( c.id IN (SELECT client_id FROM bookings) AND '1' IN (SELECT practitioner_id FROM bookings) , c.county, NULL) as county,
IF( c.id IN (SELECT client_id FROM bookings) AND '1' IN (SELECT practitioner_id FROM bookings) , c.postcode, NULL) as postcode,
IF( c.id IN (SELECT client_id FROM bookings) AND '1' IN (SELECT practitioner_id FROM bookings) , c.email, NULL) as email,
IF( c.id IN (SELECT client_id FROM bookings) AND '1' IN (SELECT practitioner_id FROM bookings) , c.dob, NULL) as dob
FROM clients c
答案 0 :(得分:3)
你应该采取不同的方法。
我猜你在相应的预订有1的从业者时想要额外的列。我不是100%肯定,因为你的查询做了一些稍微不同的事情。
但总体思路是这样的:
SELECT c.id, c.first_name, c.last_name,
(CASE WHEN b.client_id IS NOT NULL THEN c.address1 END) as address1,
. . .
FROM clients c LEFT JOIN
bookings b
ON c.id = b.client_id AND b.practitioner_id = 1;
使用您想要的其他列填写. . .
。