Comparing two values from the same select query - mysql

I have a select query which selects all products from my inventory table and joins them with two other tables (tables l_products and a_products)
SELECT
i.*,
b.title,
ROUND((i.price/100*80) - l.price,2) AS margin,
l.price AS l_price,
a.price AS a_price,
ROUND((a.price/100*80) - l.price, 2) AS l_margin
FROM inventory i
LEFT JOIN products b ON i.id = b.id
LEFT JOIN a_products a ON i.id = a.id
LEFT JOIN l_products l ON i.id = l.id
WHERE
a.condition LIKE IF(i.condition = 'New', 'New%', 'Used%')
AND l.condition LIKE IF(i.condition = 'New', 'New%', 'Used%')
This select query will normally give me a table such as...
id, title, condition, margin, l_price, a_price ...
001-new ... new 10 20 10
001-used ... used 10 25 20
002....
Now I need a condition in the query which will ignore all used products that are more expensive (have a higher a_price) than their 'new' counterparts, such as in the example above you can see that 001-used has a higher a_price than 001-new.
How can I achieve this with out having to resolve to using php

FULL JOIN this query with it self on a column which has a uniquely same value for each id prefix.
You may achieve this effect by adding another field to your SELECT call which produces same unique value for 001-new and 001-used, 002-new and 002-used...
Such value generation can be done by defining your own SQL Routine to extract first 3 characters from a column.

Related

Select rows in one table based on an id that appears in a column on a different table AND have multiple matches based on another column

This is a very difficult question for me to formulate so the title may need review. But here's my situation:
I need to select all rows from the node table that contain a row in the field_data_field_incident_type where the entity_id matches nid
and multiple field_incident_type_tid's which have the same entity_id as the nid.
This is some example data from the tables
For example a query I might want to do is
Select all nodes from node that have both field_incident_type_tid of 66 and 64
which should return the rows with the nid 98603 and 98612 from the node table.
Right now I'm doing it with left joins like this
SELECT nid
FROM node
left JOIN field_data_field_incident_type field_data_field_incident_type
ON node.nid = field_data_field_incident_type.entity_id
left JOIN field_data_field_incident_type field_data_field_incident_type_2
ON field_data_field_incident_type_2.entity_id = node.nid
WHERE field_data_field_incident_type.field_incident_type_tid = 66
AND field_data_field_incident_type_2.field_incident_type_tid = 64
;
this does work but that join is creating every permutation of incident_type_tid's and gets crazy if I keep on adding more incident_type_tid requirements
Is there a better way to do this?
The standard approach looks like this:
SELECT c.olumns
, y.ou
, a.ctually
, w.ant
FROM node c
JOIN field_data_field_incident_type y
ON y.entity_id = c.nid
WHERE y.field_incident_type_tid IN(66,64)
GROUP
BY c.nid
HAVING COUNT([DISTINCT] y.field_incident_type_tid) = 2 -- WHERE '2' is equal to the number of arguments in IN().
Please keep any comments about syntax errors to yourself.
SELECT distinct node.*,field_data_field_incident_type.field_incident_type_tid
FROM node
JOIN field_data_field_incident_type field_data_field_incident_type
ON node.nid = field_data_field_incident_type.entity_id

Selecting single max values

Say I need to pull data from several tables like so:
item 1 - from table 1
item 2 - from table 1
item 3 - from table 1 - but select only max value of item 3 from table 1
item 4 - from table 2 - but select only max value of item 4 from table 2
My query is pretty simple:
select
a.item 1,
a.item 2,
b.item 3,
c.item 4
from table 1 a
left join (select b.key_item, max(item 3) from table 1, group by key_item) b on a.key_item = b.key_item
left join (select c.key_item, max(item 4) from table 2, group by key_item) c on c.key_item = a.key_item
I am not sure if my methodology of pulling just a single max item from a table is the most efficient. Assume both tables are over a million rows. my actual sql run forever using this sql setup.
EDIT: I changed the group by clause to reflect comments made. I hope it makes a bit of sense now?
Your best bet is to add an index on table1 and table2, as follows:
ALTER TABLE table1
ADD INDEX `GoodIndexName1` (`key_item`,`item3`)
ALTER TABLE table2
ADD INDEX `GoodIndexName2` (`key_item`,`item4`)
This will allow you to use queries as described in the MySQL documentation for finding the rows holding the group-wise maximum, which appears to be what you are looking for.
Your original (edited) query should work:
select
a.item1,
a.item2,
b.item3,
c.item4
from table1 a
LEFT OUTER JOIN (
SELECT
b.key_item,
MAX(item3) AS item3
FROM table1
GROUP BY key_item
) b
ON a.key_item = b.key_item
LEFT OUTER JOIN (
SELECT
c.key_item,
MAX(item4)
FROM table2
GROUP BY key_item
) c
ON c.key_item = a.key_item
and if that performs slowly after adding the indexes, try the following too:
SELECT
a.item1,
a.item2,
b.item3,
c.item4
FROM table1 a
LEFT OUTER JOIN table1 b
ON b.key_item = a.key_item
LEFT OUTER JOIN table1 larger_b
ON larger_b.key_item = b.key_item
AND larger_b.item3 > b.item_3
LEFT OUTER JOIN table2 c
ON c.key_item = a.key_item
LEFT OUTER JOIN table2 larger_c
ON larger_c.key_item = c.key_item
AND larger_c.item4 > c.item4
WHERE larger_b.key_item IS NULL
AND larger_c.key_item IS NULL
(I have modified the table and column names only slightly, so that they conform to correct MySQL syntax. )
I work with queries that use the above structure all the time, and they perform very efficiently with indexes like the one I provided.
That said, usually I am using INNER JOINs on the b and c tables, but I don't see why your query should have any issues.
If you do experience performance problems still, report the data types of the key_item columns for each table, as if you try to join on different data types, you will generally get poor performance.

optimizing query (LEFT JOIN)

My goal is to show search results of companies both: with categories and without (not added yet). My companies table has more or less 12 000 records. Companies with categories are only more or less 200.
There are two search inputs:
$name -> name of company or category.
$id_country -> id of the country
I want to display:
1) how many results is in all database. (that's why i use: SQL_CALC_FOUND_ROWS)
2) i use LIMIT to show 10 results per page (with pagination).
My query:
SELECT SQL_CALC_FOUND_ROWS
c.*,
lc.name as langName,
lc.shortDesc,
lc.longDesc
FROM companies c
JOIN lang_companies lc USING(id_company)
LEFT JOIN categories_companies cc USING(id_company)
LEFT JOIN lang_categories lang_cat USING (id_category)
WHERE
lc.id_lang = '2' AND c.status = 1 AND c.active = 1 AND c.id_country = ".$id_country." AND
(lc.name = LCASE('".$name."') OR (lang_cat.name = LCASE('".$name."') AND lang_cat.id_lang = '2')
OR c.city = '".$name."')
GROUP BY c.id_company
ORDER BY c.id_hierarchi asc
LIMIT 0, 10
This query executes more or less 6 seconds and I want to optimize it. Could you help me?
I will be grateful for any suggestions.
Out of the FROM part of your query, you do not seem to actually use the tables which are joined with these two lines:
LEFT JOIN categories_companies cc USING(id_company)
LEFT JOIN categories cat USING (id_category)
I presume you can simply exclude them from the query, if they are not relevant through something more sublte like the join suppressing rows.

COUNT evaluate to zero if no matching records

Take the following:
SELECT
Count(a.record_id) AS newrecruits
,a.studyrecord_id
FROM
visits AS a
INNER JOIN
(
SELECT
record_id
, MAX(modtime) AS latest
FROM
visits
GROUP BY
record_id
) AS b
ON (a.record_id = b.record_id) AND (a.modtime = b.latest)
WHERE (((a.visit_type_id)=1))
GROUP BY a.studyrecord_id;
I want to amend the COUNT part to display a zero if there are no records since I assume COUNT will evaluate to Null.
I have tried the following but still get no results:
IIF(ISNULL(COUNT(a.record_id)),0,COUNT(a.record_id)) AS newrecruits
Is this an issue because the join is on record_id? I tried changing the INNER to LEFT but also received no results.
Q
How do I get the above to evaluate to zero if there are no records matching the criteria?
Edit:
To give a little detail to the reasoning.
The studies table contains a field called 'original_recruits' based on activity before use of the database.
The visits tables tracks new_recruits (Count of records for each study).
I combine these in another query (original_recruits + new_recruits)- If there have been no new recruits I still need to display the original_recruits so if there are no records I need it to evalulate to zero instead of null so the final sum still works.
It seems like you want to count records by StudyRecords.
If you need a count of zero when you have no records, you need to join to a table named StudyRecords.
Did you have one? Else this is a nonsense to ask for rows when you don't have rows!
Let's suppose the StudyRecords exists, then the query should look like something like this :
SELECT
Count(a.record_id) AS newrecruits -- a.record_id will be null if there is zero count for a studyrecord, else will contain the id
sr.Id
FROM
visits AS a
INNER JOIN
(
SELECT
record_id
, MAX(modtime) AS latest
FROM
visits
GROUP BY
record_id
) AS b
ON (a.record_id = b.record_id) AND (a.modtime = b.latest)
LEFT OUTER JOIN studyrecord sr
ON sr.Id = a.studyrecord_id
WHERE a.visit_type_id = 1
GROUP BY sr.Id
I solved the problem by amending the final query where I display the result of combining the original and new recruits to include the IIF there.
SELECT
a.*
, IIF(IsNull([totalrecruits]),consents,totalrecruits)/a.target AS prog
, IIf(IsNull([totalrecruits]),consents,totalrecruits) AS trecruits
FROM
q_latest_studies AS a
LEFT JOIN q_totalrecruitment AS b
ON a.studyrecord_id=b.studyrecord_id
;

mysql limiting join

I've done a few searches on this subject but non of the solutions seem to work so perhaps my requirement is slightly different.
Basically I have a "content" table and a "file_screenshots" table. Each row in the "file_screenshots" table has a "screenshot_content_id" column. I want to select from the "content" table, join the "file_screenshots" table but only select a maximum of 5 screenshots for any single piece of content.
If this isn't possible i'm happy to use two queries, but again i'm not sure how to limit the results to only receiving 5 screenshots per piece of content.
Here is an example query:
SELECT * FROM content
LEFT JOIN file_screenshots
ON file_screenshots.screenshot_content_id = content.content_id
WHERE content_type_id = 4
Assuming you have some sort of unique id column in your file_screenshots table, this should work for you:
SELECT
c.*,
fs.*
FROM
content c
JOIN
file_screenshots fs
ON (fs.screenshot_content_id = c.content_id)
LEFT JOIN
file_screenshots fs2
ON (fs2.screenshot_content_id = c.content_id AND fs2.id < fs.id)
GROUP BY
fs.id
HAVING
COUNT(*) < 5
ORDER BY c.content_id, fs.id
I've named the id column id. Rename it if neccessary.
If you want the 5 screenshots with the highest id, reverse the fs2.id vs. fs.id comparison.
ON (fs2.screenshot_content_id = c.content_id AND fs2.id > fs.id)