Write SQL other optimized way - mysql

I have below query which I have written like below. Actually, I want to get two diff. colors from colors table. Please look into it and can you tell me It is optimized way? Can I write below query other optimized way?
SELECT d.*,
(SELECT c.clr_title FROM colors AS c WHERE c.id = d.base_color_id) AS base_color,
(SELECT c.clr_title FROM colors AS c WHERE c.id = d.overlay_color_id) AS overlay_color
FROM indira.dress AS d
WHERE id=669;
Thanks for your help.

Here's another way to get an equivalent result:
SELECT d.*
, b.clr_title AS base_color
, o.clr_title AS overlay_color
FROM indira.dress d
LEFT
JOIN colors b ON b.id = d.base_color_id
LEFT
JOIN colors o ON b.id = d.overlay_color_id
WHERE d.id=669
The correlated subqueries in the SELECT list can be expensive for large sets. But for returning a single row, that's not going to be a performance issue, since those subqueries will get executed only once.
In a more general case, for returning lots of rows, using a JOIN is usually more efficient.
You likely already have suitable indexes. For optimum performance, you'd want an index ON indira.dress(id) (likely already the primary key) and ON colors (id) (again, likely already the primary key). There's likely no performance benefit of adding a covering index.

Here is another option. I don't know what columns you do have on dress table so you will likely have to call the ones you out in select and group but this should work.
Not sure if it would be any faster/slower but wanted to give you more options ;-)
Here it is in sql fiddle where I also show what would happen if null was given for overlay. -> http://sqlfiddle.com/#!2/ebc82/3
SELECT
d.name
,MAX(CASE WHEN d.base_color_id = c.id THEN c.clr_title ELSE NULL END) base_color
,MAX(CASE WHEN d.overlay_color_id = c.id THEN c.clr_title ELSE NULL END) overlay_color
FROM
dress d
INNER JOIN colors c ON
c.Id IN (d.base_color_id, d.overlay_color_id)
WHERE
d.id = 669
GROUP BY
d.name

Since you're restricting to a single record, it's probably just fine. But you could always join against the color table twice, like:
select
d.*
,base_color.clr_title base_color
,overlay_color.clr_title overlay_color
from
indira.dress d
left join
colors base_color on d.base_color_id = base_color.id
left join
colors overlay_color on d.overlay_color_id = overlay_color.id
where
d.id = 669

Related

how to change this mysql query to a efficient one

my table user contains these fields
id,company_id,created_by,name,image
table valet contains
id,vid,dept_id
table cart contains
id,dept_id,map_id,purchase,time
to get the details i have written this mysql query
SELECT c.id, a.id, c.purchace, c.time
FROM user a
LEFT JOIN valet b ON a.vid = b.id
AND a.is_deleted = 0
LEFT JOIN cart c ON b.dept_id = c.dept_id
WHERE a.company_id = 18
AND a.created_by = 102
AND a.is_deleted = 0
AND c.time
IN ( SELECT MAX( time ) FROM cart WHERE dept_id = b.dept_id )
from these three table i want to select last updated raw from cart along with id from user table which is mapped in valet table
this query works fine but it takes almost 15 sec to retrieve the details .
is there any way to improve this query or may be i am doing some wrong.
any help would be appreciated
For one thing, I can see that you’re running the subquery for each row. Depending on what the optimiser does, that may have an impact. max is a pretty expensive operation (there’s nothing for it but to read every row).
If you plan to update and use this query repeatedly, perhaps you should at least index the table on cart.time. This will make it much easier to find the maximum value.
MySQL has the concept of user variables, so you can set a variable to the result of the subquery, and that might help:
SELECT c.id, a.id, c.purchace, c.time
FROM
user a
LEFT JOIN valet b ON a.vid = b.id AND a.is_deleted = '0'
LEFT JOIN cart c ON b.dept_id = c.dept_id
LEFT JOIN (SELECT dept_id,max(time) as mx FROM cart GROUP BY dept_id) m on m.dept_id=c.dept_id
WHERE
a.company_id = '18'
AND a.created_by = '102'
AND a.is_deleted = '0'
AND c.time=m.mx;
Note also:
since you’re only testing a single value (max) for c.time, you should be using = not in.
I’m not sure about is why you are using strings instead of integers. I shold have though that leaving off the quotes makes more sense.
Your JOIN includes AND a.is_deleted = '0', though you make no mention of it in your table description. In any case, why is it in the JOIN and not in the WHERE clause?

Join predicate order

I'm always be amused and confused(at same time) whenever I have been to asked prepare and run Join query on Sql Console.
And the cause of most confusion is mainly based upon the fact whether/or not the ordering of join predicate hold any importances in Join results.
Example.
SELECT "zones"."name", "ip_addresses".*
FROM "ip_addresses"
INNER JOIN "zones" ON "zones"."id" = "ip_addresses"."zone_id"
WHERE "ip_addresses"."resporg_accnt_id" = 1
AND "zones"."name" = 'us-central1'
LIMIT 1;
Given the sql query, the Join predicate look like this.
... INNER JOIN "zones" ON "zones"."id" = "ip_addresses"."zone_id" WHERE "ip_addresses"."resporg_accnt_id"
Now, would it make any difference in term of performance of Join as well as the authenticity of the obtained result. If happen to change the predicate to look like this
... INNER JOIN "zones" ON "ip_addresses"."zone_id" = "zones"."id" WHERE "ip_addresses"."resporg_accnt_id"
The predicate order won't make a performance difference in your case, a simple equality condition, but personally I like to place the columns from the table I'm JOINing to on the LHS of each ON condition
SELECT ...
FROM ip_addresses ia
JOIN zones z
ON z.id = ia.zone_id
WHERE ...
The optimiser can use any index available on these columns during the JOIN and I find it easier to visualise this way.
Any additional conditions also tend to be on columns of the table being JOINed to and I find again this reads better when this table is consistently on the LHS
Not quite the same, but I did see a case where performance was affected by the choice of column to isolate
I think the JOIN looked something like
SELECT ...
FROM table_a a
JOIN table_b b
ON a.id = b.id - 1
Changing this to
SELECT ...
FROM table_a a
JOIN table_b b
ON b.id = a.id + 1
allowed the optimiser to use an index on b.id, but presumably at the cost of an index on a.id
I suspect this kind of query might need analysing on a case by case basis
Furthermore, I would probably switch your table order round too and write your original query:
SELECT z.name,
ia.*
FROM zones z
JOIN ip_addresses ia
ON ia.zone_id = z.id
AND ia.resporg_accnt_id = 1
WHERE z.name = 'us-central1'
LIMIT 1
Conceptually, you are saying "Start with the 'us-central1' zone and fetch me all the ip_addresses associated with a resporg_accnt_id of 1"
Check the EXPLAIN plans if you want to verify that there is no difference in your case

Why use letters in front of each value in MySQL query?

Why would I use letters in front of each value in my query like this?
In the database, each of these values is WITHOUT the letter in front.
SELECT c.client_id, c.client_name, c.contactperson, c.internal_comment,
IF NULL(r.region, 'Alle byer') as region, c.phone, c.email,
uu.fullname as changed_by,
(select count(p.project_id)
from projects p
where p.client_id = c.client_id and (p.is_deleted != 1 or p.is_deleted is null)
) as numProjects
FROM clients c LEFT JOIN users uu ON c.db_changed_by = uu.id
LEFT JOIN regions r ON c.region_id = r.region_id
WHERE (c.is_deleted != 1 or c.is_deleted is null)
I have tried looking it up, but I can't find it anywhere.
When in SQL you need to use more than one table for a query, you can do this:
SELECT person.name, vehicle.id FROM person, vehicle;
OR you can do it smaller, and put like this
SELECT p.name, v.id FROM person p, vehicle v;
It's only for reducing the query length, and it's useful for you
By "letters in front", I assume you mean the qualifiers on the columns c., uu. and so on. They indicate the table where the column comes from. In a sense, they are part of the definition of the column.
This is your query:
SELECT c.client_id, c.client_name, c.contactperson, c.internal_comment,
IF NULL(r.region, 'Alle byer') as region, c.phone, c.email,
uu.fullname as changed_by,
(select count(p.project_id)
from projects p
where p.client_id = c.client_id and (p.is_deleted != 1 or p.is_deleted is null)
) as numProjects
FROM clients c LEFT JOIN
users uu
ON c.db_changed_by = uu.id LEFT JOIN
regions r
ON c.region_id = r.region_id
WHERE (c.is_deleted != 1 or c.is_deleted is null)
In some cases, these are needed. Consider the on clause:
ON c.region_id = r.region_id
If you leave them out, you have:
ON region_id = region_id
The SQL compiler cannot interpret this, because it does not know where region_id comes from. Is it from clients or regions? If you used this in the select, you would have the same issue -- and it makes a difference because of the left join. This is also true in the correlated subquery.
In general, it is good practice to qualify column names for several reasons:
The query is unambiguous.
You (and others) readily know where columns are coming from.
If you modify the query and add a new table/subquery, you don't have to worry about naming conflicts.
If the underlying tables are modified to have new column names that are shared with other tables, then the query will still compile.
Consider you are accessing 2 tables and both have same column name say 'Id', In query you can easily identify those columns using letters like a.Id == d.Id if first table has alias name 'a' and second table 'b'. Or else It would be very difficult to identify which column belongs which table especially when you have common table columns.

WHERE clause if match

What is the simplest way to make part of a WHERE clause dependent on the result of a JOIN? I realize that is an extremely ambiguous and confusing question, so allow me to simply show you what I am trying to achieve:
SELECT m.member_id, m.first_name, m.last_name
FROM cal_form_answers a
INNER JOIN cal_form_elements e
USING(element_id)
INNER JOIN cal_forms f
USING(form_id)
LEFT JOIN members m
USING(member_id)
WHERE f.org_id = ?
AND m.org_id = ?
AND e.form_id = ?
GROUP BY a.member_id
ORDER BY a.member_id
First, note that the question marks are not invalid syntax—I am using Codeigniter, which uses them as bound parameters.
Line 10 (AND m.org_id = ?) is dependent on whether or not the LEFT JOIN actually finds something. If there is no match in the members table, then Line 10 becomes unnecessary. In fact, it becomes a problem. I would like to limit results by Line 10 unless there is no match in the members table. In that event, I would simply like to ignore that part of the WHERE clause.
I believe this can be achieved using subqueries, though I am admittedly unsure how to work out the syntax. Is there any other way? If yes, how else can this result be achieved? In the event there is no other way, can somebody demonstrate an implementation of a subquery for this situation, and explain how it works?
Thank you!
If a LEFT JOIN does not match a record, then those LEFT JOINed fields are null. Why not just check if that field IS NULL, and when it is not then check it.)
SELECT m.member_id, m.first_name, m.last_name
FROM cal_form_answers a
INNER JOIN cal_form_elements e
USING(element_id)
INNER JOIN cal_forms f
USING(form_id)
LEFT JOIN members m
USING(member_id)
WHERE f.org_id = ?
AND (m.org_id = ? OR m.org_id IS NULL)
AND e.form_id = ?
GROUP BY a.member_id
ORDER BY a.member_id

Mysql - db-select with several joins and tablestructure

I am using the following mysql select-query with several joins. I am wondering if this is how a somewhat good select-statement should look like:
SELECT *
FROM table_news AS a
INNER JOIN table_cat AS b ON a.cat_id = b.id
INNER JOIN table_countries AS c ON a.country_id = c.id
INNER JOIN table_addresses AS d ON a.id = d.news_id
WHERE a.deleted = 0
AND a.hidden = 0
AND a.cat_id = ".$search_cat."
AND a.country_id = ".$search_country."
AND a.title LIKE '%".$search_string."%'
OR a.deleted = 0
AND a.hidden = 0
AND a.cat_id = ".$search_cat."
AND a.country_id = ".$search_country."
AND a.subtitle LIKE '%".$search_string."%'"
It seems to be a lot of joins. Even though table b and table c contain only 3 or 4 fields, I wonder if the number of joins would clearly slow down the search on the starting-page?
Would it be better to put the fields from table d (street, city and so on) back into the main-table, as they should be needed most of the time this query is executed?
Thanx in advance,
Jayden
I don't think there is necessarily anything wrong with having three joins. There are a couple of things you can do to make sure the query is optimised.
Firstly, you should never do SELECT * - instead explicitly state what fields you want to return from the database.
Also, I would create indexes on all the fields you have in the where clause, and all of the fields you are joining. This can be a little bit of a trade off - for example if you are doing a lot of write operations then there is a hit because you need to write to the index everytime.