MySQL CASE when SELECT - mysql

I have the following query:
SELECT CASE WHEN `def_spell`.`type` = 0 THEN `spells_damage`.*
WHEN `def_spell`.`type` = 1 THEN `spells_weaken`.*
END
FROM `def_spell`
LEFT JOIN `spells_damage` ON `def_spell`.`id` = `spells_damage`.`spell_id`
LEFT JOIN `spells_weaken` ON `def_spell`.`id` = `spells_weaken`.`spell_id`
WHERE `def_spell`.`id` = 1;
Hopefully that makes sense... I'm basically trying to select everything from spells_damage providing type is 0 and everything from spells_weaken providing type is 1.
I'd also like to select everything from def_spell regardless.
Can someone please fix the query? I've never used cases like this before and not sure how to.

You can't use a CASE to choose between the output of the two tables like that.
Unfortunately, that's the easy bit; working out (a) what you're trying to do and (b) achieving an equivalent result is going to take a little longer.
It would be easier if you gave us information about the columns in the Spells_Weaken and Spells_Damage table. Presumably, there are some differences; otherwise, you'd have a single table. Indeed, a single Spells table might still be a better design.
Let's put doubts aside. Assuming that the Spells_Weaken and Spells_Damage tables are UNION-compatible, you can use a UNION to achieve the result:
SELECT s.*, d.*
FROM def_spell AS s
LEFT JOIN spells_damage AS d ON s.id = d.spell_id
WHERE s.type = 0
AND s.id = 1
UNION
SELECT s.*, w.*
FROM def_spell AS s
LEFT JOIN spells_weaken AS w ON s.id = w.spell_id
WHERE s.type = 1
AND s.id = 1;

You won't be able to do that. You will need to either split it into two queries, or manually specify each of the columns with the CASE statement.
SELECT CASE WHEN a.`type` = 0 THEN b.col1
WHEN a.`type` = 1 THEN c.col1
END AS col1
, CASE WHEN a.`type` = 0 THEN b.col2
WHEN a.`type` = 1 THEN c.col2
END AS col2
FROM `def_spell` a
LEFT JOIN `spells_damage` b ON a.`id` = b.`spell_id`
LEFT JOIN `spells_weaken` c ON a.`id` = c.`spell_id`
WHERE a.`id` = 1;

Related

this Query is taking 15 seconds

i added indexes as well but still it is taking 13 sec
I added compound index for all the columns that i've used here
SELECT carrierbil2_.IDENTITY AS col_0_0_,
carrier4_.CARRIER_NAME AS col_1_0_,
carrier4_.IDENTITY AS col_2_0_,
carrier4_.CARRIER_ID AS col_3_0_,
shipmentor0_.EXTERNAL_REFERENCE_ID AS col_4_0_,
invoicedet5_.INVOICE_NUMBER AS col_5_0_,`enter code here`
shipmentca1_.CARRIER_REFERENCE_NUMBER AS col_6_0_,
SUM(shipmentco9_.RATED_COST) AS col_7_0_,
SUM(shipmentco9_.COST) AS col_8_0_,
invoice6_.TOTAL_PAID_AMOUNT AS col_9_0_,
invoice6_.INVOICE_GENERATED_DATE AS col_10_0_,
shipmentor0_.ACTUAL_SHIP_DATE AS col_11_0_,
bolstatus15_.BOL_STATUS_ID AS col_12_0_,
shipmentlo10_.LOCATION_NAME AS col_13_0_,
country11_.COUNTRY_NAME AS col_14_0_,
postal14_.POSTAL_CODE AS col_15_0_,
state12_.STATE_NAME AS col_16_0_,
city13_.CITY_NAME AS col_17_0_,
shipmentlo16_.LOCATION_NAME AS col_18_0_,
country17_.COUNTRY_NAME AS col_19_0_,
postal20_.POSTAL_CODE AS col_20_0_,
state18_.STATE_NAME AS col_21_0_,
city19_.CITY_NAME AS col_22_0_,
shipmentor0_.IDENTITY AS col_23_0_,
shipmentca1_.IDENTITY AS col_24_0_,
shipmentno7_.NOTE AS col_25_0_
FROM
SHIPMENT_ORDER shipmentor0_
INNER JOIN
SHIPMENT_CARRIER shipmentca1_ ON shipmentor0_.SHIPMENT_ORDER_ID = shipmentca1_.SHIPMENT_ORDER_ID
AND (shipmentca1_.IS_DELETED = 0)
LEFT OUTER JOIN
CARRIER_BILL_DETAILS carrierbil2_ ON shipmentca1_.SHIPMENT_CARRIER_ID = carrierbil2_.SHIPMENT_CARRIER_ID
LEFT OUTER JOIN
CARRIER_BILLS carrierbil3_ ON carrierbil2_.CARRIER_BILL_ID = carrierbil3_.CARRIER_BILL_ID
INNER JOIN
CARRIER carrier4_ ON shipmentca1_.CARRIER_ID = carrier4_.CARRIER_ID
LEFT OUTER JOIN
INVOICE_DETAILS invoicedet5_ ON shipmentor0_.SHIPMENT_ORDER_ID = invoicedet5_.SHIPMENT_ORDER_ID
LEFT OUTER JOIN
INVOICE invoice6_ ON invoicedet5_.INVOICE_ID = invoice6_.INVOICE_ID
LEFT OUTER JOIN
SHIPMENT_NOTES shipmentno7_ ON shipmentor0_.SHIPMENT_ORDER_ID = shipmentno7_.SHIPMENT_ORDER_ID
AND (shipmentno7_.NOTE_TYPE = 4)
LEFT OUTER JOIN
SHIPMENT_COST shipmentco8_ ON shipmentor0_.SHIPMENT_ORDER_ID = shipmentco8_.SHIPMENT_ID
LEFT OUTER JOIN
SHIPMENT_COST_DETAILS shipmentco9_ ON shipmentco8_.SHIPMENT_COST_ID = shipmentco9_.SHIPMENT_COST_ID
AND (shipmentco9_.IS_DELETED = 0)
LEFT OUTER JOIN
SHIPMENT_LOCATION shipmentlo10_ ON shipmentor0_.ORIGIN_ID = shipmentlo10_.SHIPMENT_LOCATION_ID
AND (shipmentlo10_.LOCATION_TYPE_ID = 3)
LEFT OUTER JOIN
COUNTRY country11_ ON shipmentlo10_.COUNTRY_ID = country11_.COUNTRY_ID
LEFT OUTER JOIN
STATE state12_ ON shipmentlo10_.STATE_ID = state12_.STATE_ID
LEFT OUTER JOIN
CITY city13_ ON shipmentlo10_.CITY_ID = city13_.CITY_ID
LEFT OUTER JOIN
POSTAL postal14_ ON shipmentlo10_.POSTAL_ID = postal14_.POSTAL_ID
LEFT OUTER JOIN
BOL_STATUS bolstatus15_ ON shipmentor0_.ORDER_STATUS = bolstatus15_.BOL_STATUS_ID
LEFT OUTER JOIN
SHIPMENT_LOCATION shipmentlo16_ ON shipmentor0_.DESTINATION_LOCATION_ID = shipmentlo16_.SHIPMENT_LOCATION_ID
AND (shipmentlo16_.LOCATION_TYPE_ID = 4)
LEFT OUTER JOIN
COUNTRY country17_ ON shipmentlo16_.COUNTRY_ID = country17_.COUNTRY_ID
LEFT OUTER JOIN
STATE state18_ ON shipmentlo16_.STATE_ID = state18_.STATE_ID
LEFT OUTER JOIN
CITY city19_ ON shipmentlo16_.CITY_ID = city19_.CITY_ID
LEFT OUTER JOIN
POSTAL postal20_ ON shipmentlo16_.POSTAL_ID = postal20_.POSTAL_ID
CROSS JOIN
CLIENT client21_
WHERE
shipmentor0_.CLIENT_ID = client21_.CLIENT_ID
AND bolstatus15_.SEQUENCE_ID >= 700
AND (carrierbil3_.IS_APPROVED = 0
OR carrierbil3_.IS_APPROVED IS NULL)
AND (carrierbil3_.IS_DELETED = 0
OR carrierbil3_.IS_DELETED IS NULL)
AND (carrierbil2_.IS_DELETED = 0
OR carrierbil2_.IS_DELETED IS NULL)
AND (shipmentor0_.IS_DELETED = 0
OR shipmentor0_.IS_DELETED IS NULL)
GROUP BY invoice6_.INVOICE_GENERATED_DATE , shipmentca1_.IDENTITY , invoicedet5_.INVOICE_NUMBER , invoice6_.TOTAL_PAID_AMOUNT , shipmentca1_.CARRIER_REFERENCE_NUMBER , carrier4_.CARRIER_ID , CAST(carrier4_.IDENTITY AS SIGNED) , carrier4_.CARRIER_NAME , CAST(carrierbil2_.IDENTITY AS SIGNED) , shipmentor0_.SHIPMENT_ORDER_ID , shipmentno7_.NOTE , shipmentor0_.EXTERNAL_REFERENCE_ID , shipmentlo10_.LOCATION_NAME , country11_.COUNTRY_NAME , postal14_.POSTAL_CODE , state12_.STATE_NAME , city13_.CITY_NAME , shipmentlo16_.LOCATION_NAME , country17_.COUNTRY_NAME , postal20_.POSTAL_CODE , state18_.STATE_NAME , city19_.CITY_NAME , shipmentor0_.IDENTITY
ORDER BY shipmentor0_.SHIPMENT_ORDER_ID DESC;
The indexes are mostly useless because of OR, as in
AND (carrierbil3_.IS_APPROVED = 0
OR carrierbil3_.IS_APPROVED IS NULL)
The simple way to fix that is to pick either 0 or NULL to represent the flag. Then make sure all the data is consistent, and change the WHERE to just check for the one case.
Do you really mean
CROSS JOIN
CLIENT client21_
That is likely to be a performance-killer and generate a huge resultset.
Never mind. You have the ON in WHERE. Please use ON for relations and WHERE for filtering.
WHERE
shipmentor0_.CLIENT_ID = client21_.CLIENT_ID
I see a mixture of LEFT JOIN and JOIN. Check that the LEFT JOINs really need to be LEFT; that is, the 'right' table might have missing data.
To discuss further, please provide EXPLAIN SELECT ....
Eschew over-normalization:
You have 5 tables to describe a location (name, country, postal, state, city). Instead, I recommend a single table with those 5 columns. This, alone, would get rid of 8 JOINs.
CAST(carrier4_.IDENTITY AS SIGNED) -- Can't you fix the datatype to be SIGNED, or allow the value to be UNSIGNED?
But perhaps the main performance-killer is the "explode-implode" syndrone. First, it does a lot of JOINs, building a huge intermediate table, then it collapses that by doing GROUP BY. The remedy is
SELECT ...
FROM ( SELECT SUM(...), SUM(...) FROM ... GROUP BY ... ) AS a
JOIN ((whatever else is needed));
That is, first devise a minimal "derived table" that does the GROUP BY (and/or ORDER BY and/or LIMIT). Then see what else is needed to complete the query (namely all the normalization lookups).
After you have acted on most of my comments, we can discuss whether you have the optimal indexes. (It is premature to do so now.) If so, please start a new Question; it would be too much clutter to add to this one.
First of all, that's a lot of joins. However, the main reason your query is taking a significant time is because you're adding an order by clause. You need to figure out a way to avoid it, or may be come up with a different strategy

Order query output according to 'is in table/ is not in table'

I have the following Database Design:
Database Design
I want to get all Information from table 'info' where the id IS NOT in table 'archived'. To do so I wrote:
SELECT *
FROM traffic_info i
LEFT JOIN
traffic_info_archived a ON (i.info_id = a.info_id)
WHERE
i.branch_id = 4 AND i.user_id = 7 a.info_id IS NULL ORDER BY i.info_date_from ASC
This works as expected.
The next challenge is to only show information that are also included in the 'published' table. To get this done I have expanded my previous query to :
SELECT *
FROM traffic_info i
LEFT JOIN
traffic_info_archived a ON (i.info_id = a.info_id)
RIGHT JOIN
traffic_info_publised p ON (i.info_id = p.info_id)
WHERE
i.branch_id = 4 AND a.info_id AND i.user_id = 7 IS NULL ORDER BY i.info_date_from ASC
This does also work as expected.
The final challenge is to Order this result according to table 'read'. Information´s id that are NOT in table 'read' should be ordered ASC. But even if its id does not appear in table 'read' they should not be excluded from the query output. BUT the primary ORDER should be
i.info_date_from ASC
I hope this is understandable, my English is not the best :) If not, please comment and I will do my best to make it understandable. Hope some can help!
I´ve tried to create a SQLFiddle, but I wasn´t able to create a runnable example, sorry for that.
UPADTE:
Using the approach from #Dylan Su
SELECT *
FROM traffic_info i
LEFT JOIN
traffic_info_archived a ON (i.info_id = a.info_id)
INNER JOIN
traffic_info_publised p ON (i.info_id = p.info_id)
WHERE
i.branch_id = 4 AND a.info_id AND i.user_id = 7 IS NULL
ORDER BY
CASE WHEN NOT EXISTS(SELECT 1 FROM read WHERE i.info_id = read.info_id)
THEN i.info_date_from END ASC;
the goal is nearer then it ever was :)
Sample Data output
Both entries marked with a red "X" are in table read. Therefore id 3 should be last the, in the middle 1 and 2 at the top.
So the last thing to archive is to do the correct order of table read. I´ve tried sth like:
(SELECT 1 FROM traffic_info_read WHERE i.info_id = traffic_info_read.info_id ORDER BY traffic_info_read.info_id DESC)
But that didn´t had any influnce.
Try this:
SELECT *
FROM traffic_info i
LEFT JOIN
traffic_info_archived a ON (i.info_id = a.info_id)
INNER JOIN
traffic_info_publised p ON (i.info_id = p.info_id)
WHERE
i.branch_id = 4 AND a.info_id AND i.user_id = 7 IS NULL
ORDER BY
EXISTS(SELECT 1 FROM read WHERE i.info_id = read.info_id) ASC,
i.info_date_from ASC;
The Answer of #Dylan Su is absolutely correct and I won´t unmark it as accepted.
However, based on the Information I gained from the conversation I have created another solution, that doesn´t make use of sub query.
I heard that using just JOIN´s will result in better performance, I don´t know if it´s correct and I don´t have that much test data currently to find out, but here is the solution using no sub query.
SELECT *
FROM traffic_info i
LEFT JOIN
traffic_info_archived a ON (i.info_id = a.info_id)
INNER JOIN
traffic_info_published p ON (i.info_id = p.info_id)
LEFT JOIN
traffic_info_read r ON (i.info_id = r.info_id)
WHERE
i.branch_id = 4 AND a.info_id IS NULL ORDER BY r.info_id IS NULL DESC, i.info_date_from ASC
;

How can I update some rows using an inner join in SQL in a way which will work on both mysql and postgres?

I have this SQL which updates rows on MySQL, but I need to rewrite it so that it will work on PostgreSQL as well. I'm aware that I can make it work for PostgreSQL using a different syntax, but I need one statement which will work for both systems.
UPDATE {coursework_feedbacks} AS f
INNER JOIN {coursework_submissions} AS s
ON f.submissionid = s.id
INNER JOIN {coursework} c
ON s.courseworkid = c.id
SET f.stage_identifier = 'assessor_1'
WHERE f.ismoderation = 0
AND f.isfinalgrade = 1
AND c.numberofmarkers = 1
As this particular case can be phrased with a correlated subquery, you can just write:
UPDATE {coursework_feedbacks} AS f
SET f.stage_identifier = 'assessor_1'
WHERE f.ismoderation = 0
AND f.isfinalgrade = 1
AND EXISTS (
SELECT 1
FROM {coursework_submissions} AS s
INNER JOIN {coursework} c ON s.courseworkid = c.id
WHERE f.submissionid = s.id AND c.numberofmarkers = 1
);
but in the more general case where that isn't true (say, where you need to update a value based on the result of the join) I don't know if there is a portable, efficient way.

MySQL statement, JOIN

I have these tables :
I don't know how I can write a statement, that takes emails from Table "Firm", that have Location_id = '1' and Category_id = '130';
I know that I should use JOINs, but I'm not sure how to go from there.
SELECT Firm.email
FROM Firm
INNER JOIN FirmID ON Firm.firma_id = FirmID.firma_id
WHERE FirmID.location_id = '1'
AND FirmID.Category_id = '130'
Should be as simple as doing the following:
SELECT email
FROM Firm, FirmID
WHERE Firm.firma_id = FirmID.firma_id
AND FirmID.location_id = 1
AND FirmID.category_id = 130;
It does a join behind the scenes, but can be a bit clearer to understand than using the JOIN keyword.
You could do:
SELECT f.email
FROM Firm f
WHERE f.firma_id =
(
SELECT ff.firma_id
FROM FirmID ff
WHERE ff.location_id = 1
AND ff.category_id = 130
)
Using an inner select.
But using JOINS is in the long term the way to go, what have you tried and what's not working?

Why does adding this extra condition to my query make it take considerably longer to execute

This is the query I'm talking about:
SELECT COUNT
FROM Note N, DatePCC D
WHERE D.codClient = '2' AND
((D.CodPCC = N.CodPCC AND D.TipPCC = N.TipPCC) OR (D.CodPCC = N.CodPCCOA AND D.TipPCC = N.Relatie))
AND (N.user = 'Server' OR N.user = 'ADMIN' OR N.user = 'Simona' OR N.user =
'Viorel' OR N.user = 'Dan' OR N.user = 'Razvan') AND (N.TipNota = 'Telefon' OR N.TipNota =
'Messenger' OR N.TipNota = 'Telefon esuat' OR N.TipNota = 'Email' OR N.TipNota = 'Evaluare
curs' OR N.TipNota = 'Corespondenta' OR N.TipNota = 'Vizita') AND
(DATE(N.DataInregistrarii) >= '2000-01-01' AND DATE(N.DataInregistrarii) <= '2012-01-25')
AND 1
The problem come from the line i've singled out. When I use it as simply
(D.CodPCC = N.CodPCC AND D.TipPCC = N.TipPCC)
the query runs almost instantly but after I add the second part it locks up our database. I can't, for the life of me, figure out why it impacts the duration so much since it's simply another two comparisons among many other.
What the query does is select stuff from N X D Where either these two (CodPCC, TipPCC) from N coincide with CodPCC and TipPCC from D or (CodPCCOA, Relatie) from N coincide with the same two rows from D.
Any idea how those two simple comparisons are changing the query in such a huge way? or how I could change it to work properly?
The big difference is because you are changing a simple inner join into an expression that has to be evaluated on a cross join between the tables.
You shouldn't write your join that way in the first place, but use the join keyword:
select COUNT
from Note N
inner join DatePCC D on D.codClient = '2' and D.CodPCC = N.CodPCC and D.TipPCC = N.TipPC
where ...
To make the new query efficient, you should make two left joins against the same table. That way the database can use index for each join instead of making a cross join.
select COUNT
from Note N
left join DatePCC D on D.codClient = '2' and D.CodPCC = N.CodPCC and D.TipPCC = N.TipPC
left join DatePCC D2 on D2.codClinent = '2' and D.CodPCC = N.CodPCCOA AND D.TipPCC = N.Relatie
where ...
You can also try if an inner join is efficient with the two sets of conditions, but it's possible that the database can't optimise that into a good query.