MySQL query to convert rows of multiple tables into columns
P粉882357979
2023-08-13 16:02:22
<p>I need to ask you about MySQL select query from 3 tables. </p>
<p>I have 3 similar tables: </p>
<p><strong>table_1</strong></p>
<pre class="brush:php;toolbar:false;">menu_id | menu_name
1 | Menu 1
2 | Menu 2</pre>
<p><strong>table_2</strong></p>
<pre class="brush:php;toolbar:false;">item_id | menu_id | item_name
1 | 1 | Project 1
2 | 1 | Project 2
3 | 2 | Project 3
4 | 2 | Project 4</pre>
<p><strong>table_3</strong></p>
<pre class="brush:php;toolbar:false;">price_id | item_id | currency_code | price
1 | 1 | EUR | 3.65
2 | 1 | USD | 3.45
3 | 2 | EUR | 9.00
4 | 4 | LEV | 4.85
5 | 4 | RON | 9.60</pre>
<p>I need to perform the following output SELECT:</p>
<pre class="brush:php;toolbar:false;">item_id | item_name | menu_id | menu_name | p_EUR | p_USD | p_GBP | p_RON | p_LEV
1 | item 1 | 1 | menu 1 | 3.65 | 3.45 | 0 | 0 | 0
2 | item 2 | 1 | menu 1 | 9.00 | 0 | 0 | 0 | 0
3 | item 3 | 2 | menu 2 | 0 | 0 | 0 | 0 | 0
4 | Item 4 | 2 | Menu 2 | 0 | 0 | 0 | 9.60 | 4.85</pre>
<p>I wish to populate the columns of the query (p_EUR, p_USD, etc.) with rows from table_3. If there are no matching records, 0 or NULL is returned.
Tables are joined via <code>table_1.menu_id=table_2.menu_id</code> and <code>table_2.item_id=table_3.item_id</code>. </p>
You can use
case when
If you need to convert null to 0, you can use
COALESCE
as shown belowCOALESCE(MAX(CASE WHEN t3.currency_code = 'LEV' THEN t3.price END), 0) AS p_LEV