Perform a SQL Query - mysql

I have this query in PHP MySQL PDO:
SELECT p.las_plano_id, p.mensalidade_diferenciada, v.las_tipos_planos_id, t.valor_mensalidade
FROM isw_planos AS p
INNER JOIN isw_planos_vinculos AS v
ON p.las_plano_id =
(SELECT v.las_plano_id
FROM isw_planos_vinculos
WHERE v.data_encerramento IS NULL
ORDER BY v.data_adesao
DESC LIMIT 1)
INNER JOIN isw_planos_tipos AS t
ON v.las_tipos_planos_id = t.id
WHERE p.ativo = 1
But.. the result generate a long delay.. it's possible to perform this query to execute more fast?
Thnaks..

I suspect the error is with v.:
This looks wrong: SELECT v.las_plano_id ... since v is outside the subquery. Please check the aliases used.
If removing v. does not help, please provide SHOW CREATE TABLE so we can see the indexes, etc.

Related

mysqli select over two tables - speed optimisation

SQL-Select:
SELECT mf.*
, ma.Titel
FROM `sporttype_fragebogen` as mf
, sporttypen_auswertung as ma
WHERE mf.SessionID = ma.SessionID
ORDER
BY mf.ID
In both tabels there are around 17'000 data set. My problem is, that it takes quite long to the the results. How can i speed-optimise my SQL Select?
I also tried with a join, but same "Problem":
SELECT *
FROM `sporttype_fragebogen`
JOIN sporttypen_auswertung
ON sporttype_fragebogen.SessionID = sporttypen_auswertung.SessionID
ORDER
BY sporttype_fragebogen.ID
Thanks for help

Mysql - Add if condition in the Mysql Query or a where clause

I have written a join query in MySQL which works well and shows the result.
I am trying to write a MySQL query that shows 2 additional columns with some calculations
If isPercent=1 then
New Column1=price*currentPercent/100
New Column2=LineItemQuantity*price
I tried to write this query in PHP but since there are 100,000s records it is timing out.
Here is MySQL query and the results shown below
Select
wl.LineItems_LineItemID,
wl.LineItemQuantity,
pj.IsPercent,
pj.CurrentPercent,
pj.CurrentRate,
cb.Price
from
WorkOrderLineItems wl,
PayScaleLoaclJObCodes pj,
ClientBillingRates cb
where
wl.LineItems_LineItemID=pj.JobCodeID
AND wl.LineItems_LineItemID=cb.ClientBillingRates_ID
AND pj.PayScalesLocal_ID='33'
I would write the query this way:
SELECT
wl.LineItems_LineItemID,
wl.LineItemQuantity,
pj.IsPercent,
pj.CurrentPercent,
pj.CurrentRate,
cb.Price,
IF(pj.IsPercent=1, cb.Price*pj.CurrentPercent/100, NULL) AS `New Column 1`,
IF(pj.IsPercent=1, wl.LineItemQuantity*cb.Price, NULL) AS `New Column 2`
FROM
WorkOrderLineItems wl
JOIN PayScaleLoaclJObCodes pj ON wl.LineItems_LineItemID = pj.JobCodeID
JOIN ClientBillingRates cb ON wl.LineItems_LineItemID = cb.ClientBillingRates_ID
WHERE pj.PayScalesLocal_ID = '33'
As in the comments above, I encourage you to use JOIN syntax instead of relying on old-fashioned comma-style joins.
As for the query timing out, I would guess that you don't have the right indexes to support this query. If you want help with query optimization, you should run SHOW CREATE TABLE <tablename> for each table in your query, and post the output in your question.

Consults with subqueries and use of regexp

I am trying to identify users that can receive medicines produce interactions. For that I have used this code:
SELECT c.user, COUNT(DISTINCT c.user)
FROM mytable AS c
JOIN (SELECT id_beneficiario, mes
FROM mytable
WHERE codigo_atc REGEXP 'C01BD01|N06AA09|J01FA10|J01MA02|J01FA09|N05AH02|L01XE06|R06AA02|A03FA03|
L04AA27|J02AC01|N06AB03|C03CA01|N05AD01|C03AA03|J02AB02|J01MA12|N05AN01|J01XD01|J05AE04|L01XE08|
N05AH03|N05AH04|N05AX08|J05AE03|J05AE01|C07AA07|L04AD02|M03BX02|N06AX05|J01EE03') AS d
ON c.user = d.user AND c.mes = d.mes
WHERE (c.codigo_atc REGEXP 'C01BD01|N06AA09|J01FA10|J01MA02|J01FA09|N05AH02|L01XE06|R06AA02|A03FA03|
L04AA27|J02AC01|N06AB03|C03CA01|N05AD01|C03AA03|J02AB02|J01MA12|N05AN01|J01XD01|J05AE04|L01XE08|
N05AH03|N05AH04|N05AX08|J05AE03|J05AE01|C07AA07|L04AD02|M03BX02|N06AX05|J01EE03')
GROUP BY c.user;
I am working local and the consult take too much time and apper the next Error: Error code: 2013. Lost conection to MYSQL server during query. Would be possible optimize my code to avoid the error?
Can this work for you?
WHERE codigo_atc IN ('C01BD01','N06AA09','J01FA10','J01MA02','J01FA09',
'N05AH02','L01XE06','R06AA02','A03FA03','L04AA27',
'J02AC01','N06AB03','C03CA01','N05AD01', etc)
This IN clause will return true if codigo_atc matches any of the values in the (list).
SQL is far better at set logic than it is at regular expression matching.
You can try with a in instead of a regexp..
Could be this is more performant
SELECT c.user, COUNT(DISTINCT c.user)
FROM mytable AS c
JOIN (SELECT id_beneficiario, mes
FROM mytable
WHERE codigo_atc IN ('C01BD01','N06AA09','J01FA10','J01MA02','J01FA09','N05AH02','L01XE06','R06AA02','A03FA03','
L04AA27','J02AC01','N06AB03','C03CA01','N05AD01','C03AA03','J02AB02','J01MA12','N05AN01','J01XD01','J05AE04','L01XE08','
N05AH03','N05AH04','N05AX08','J05AE03','J05AE01','C07AA07','L04AD02','M03BX02','N06AX05','J01EE03') AS d
ON c.user = d.user AND c.mes = d.mes
WHERE c.codigo_atc IN ('C01BD01','N06AA09','J01FA10','J01MA02','J01FA09','N05AH02','L01XE06','R06AA02','A03FA03','
L04AA27','J02AC01','N06AB03','C03CA01','N05AD01','C03AA03','J02AB02','J01MA12','N05AN01','J01XD01','J05AE04','L01XE08','
N05AH03','N05AH04','N05AX08','J05AE03','J05AE01','C07AA07','L04AD02','M03BX02','N06AX05','J01EE03')
GROUP BY c.user;
but if you explain your related table schema and what you want obtain could is possible write a more simple query

MySQL QUERY in preparing for too long

The following SQL has a preparing time of 30+ second. Is the SQL which is wrong, or the fact that I have close to one million result in the database? Can this SQL be optimized not to have it in preparing for that long?
UPDATE url_source_wp SET hash="ASDF2"
WHERE (url_source_wp.id NOT IN (
SELECT url_done_wp.url_source_wp FROM url_done_wp WHERE url_done_wp.url_group = 4)
)
AND (hash IS NULL) LIMIT 50
If preparation is your issue, you can pre compile it to a stored procedure.
See this :http://dev.mysql.com/doc/refman/5.0/en/stored-routines.html
It seems like you could more optimally do this update across a JOIN, avoiding the use of the sub-select.
UPDATE
url_source_wp AS s
INNER JOIN url_done_wp AS d
ON s.id = d.url_source_wp
SET
s.hash = 'ASDF2'
WHERE
s.hash IS NULL
AND d.url_group = 4
You need to make sure you have indexes on s.id, d.url_source_wp, s.hash, and d.url_group. Also, note that you can't use LIMIT with multi-table syntax, so if this is important this suggestion will likely not work for you.

MySQL COUNT() causing empty array() return

MySQL Server Version: Server version: 4.1.14
MySQL client version: 3.23.49
Tables under discussion: ads_list and ads_cate.
Table Relationship: ads_cate has many ads_list.
Keyed by: ads_cate.id = ads_list.Category.
I am not sure what is going on here, but I am trying to use COUNT() in a simple agreggate query, and I get blank output.
Here is a simple example, this returns expected results:
$queryCats = "SELECT id, cateName FROM ads_cate ORDER BY cateName";
But if I modify it to add the COUNT() and the other query data I get no array return w/ print_r() (no results)?
$queryCats = "SELECT ads_cate.cateName, ads_list.COUNT(ads_cate.id),
FROM ads_cate INNER JOIN ads_list
ON ads_cate.id = ads_list.category
GROUP BY cateName ORDER BY cateName";
Ultimately, I am trying to get a count of ad_list items in each category.
Is there a MySQL version conflict on what I am trying to do here?
NOTE: I spent some time breaking this down, item by item and the COUNT() seems to cause the array() to disappear. And the the JOIN seemed to do the same thing... It does not help I am developing this on a Yahoo server with no access to the php or mysql error settings.
I think your COUNT syntax is wrong. It should be:
COUNT(ads_cate.id)
or
COUNT(ads_list.id)
depending on what you are counting.
Count is an aggregate. means ever return result set at least one
here you be try count ads_list.id not null but that wrong. how say Myke Count(ads_cate.id) or Count(ads_list.id) is better approach
you have inner join ads_cate.id = ads_list.category so Count(ads_cate.id) or COUNT(ads_list.id) is not necessary just count(*)
now if you dont want null add having
only match
SELECT ads_cate.cateName, COUNT(*),
FROM ads_cate INNER JOIN ads_list
ON ads_cate.id = ads_list.category
GROUP BY cateName
having not count(*) is null
ORDER BY cateName
all
SELECT ads_cate.cateName, IFNULL(COUNT(*),0),
FROM ads_cate LEFT JOIN ads_list
ON ads_cate.id = ads_list.category
GROUP BY cateName
ORDER BY cateName
Did you try:
$queryCats = "SELECT ads_cate.cateName, COUNT(ads_cate.id)
FROM ads_cate
JOIN ads_list ON ads_cate.id = ads_list.category
GROUP BY ads_cate.cateName";
I am guessing that you need the category to be in the list, in that case the query here should work. Try it without the ORDER BY first.
You were probably getting errors. Check your server logs.
Also, see what happens when you try this:
SELECT COUNT(*), category
FROM ads_list
GROUP BY category
Your array is empty or disappear because your query has errors:
there should be no comma before the FROM
the "ads_list." prefix before COUNT is incorrect
Please try running that query directly in MySQL and you'll see the errors. Or try echoing the output using mysql_error().
Now, some other points related to your query:
there is no need to do ORDER BY because GROUP BY by default sorts on the grouped column
you are doing a count on the wrong column that will always give you 1
Perhaps you are trying to retrieve the count of ads_list per ads_cate? This might be your query then:
SELECT `ads_cate`.`cateName`, COUNT(`ads_list`.`category`) `cnt_ads_list`
FROM `ads_cate`
INNER JOIN `ads_list` ON `ads_cate`.`id` = `ads_list`.`category`
GROUP BY `cateName`;
Hope it helps?