MySQL Get One Column Only Once - mysql

I have 2 MySQL tables in which I get data from in one query
"tables" table:
"checks" table:
The query I have been trying and the result of it:
SELECT tables.tableName, tables.tableRes, tables.tableResFor, checks.chkID, checks.chkDate, checks.chkStatus
FROM tables
LEFT JOIN checks ON tables.tableID=checks.chkTable
WHERE tables.tableID=3
ORDER BY checks.chkStatus DESC, checks.chkID ASC
Here are the problems
If there were no results from the query, I need the tableName column which comes out never null, so other columns can be null (works now)
I don't want to get the rows after first row, if the chkStatus column is 1 or 0 or null, shortly I need the rows with 2 on chkStatus, if the first row is 0, 1 or null, I don't need the other rows...
Thanks in advance, I have been working on this problem for more than 10 hours...

I need the other checks where chkStatus is 2 so, add the condition to the join
SELECT
tables.tableName
, tables.tableRes
, tables.tableResFor
, checks.chkID
, checks.chkDate
, checks.chkStatus
FROM tables
LEFT JOIN checks ON tables.tableID = checks.chkTable AND chkStatus = 2
WHERE tables.tableID = 3

Related

Use subquery in mysql

The query below gives me 2 out of the 3 answers I'm looking for. On the sub-query select I get null instead of no
the 3 possible values for column name isCyl could be blank, yes, no
I'm not sure if the sub-query is the best way to go about it, but I don't know how else to re-state the query.
The schedule table has a series of columns to show what tasks must be completed on an assignment. Related tables store the results of the tasks if they were assigned to be completed. So I need to test if a specific task was scheduled. If so, then I need to see if the results of the task have been recorded in the related table. For brevity I am only showing one of the columns here.
SELECT s.`reckey`,
if(s.cylinders="T",
(select
if(c.areckey is not null,
"yes",
"no"
)
from cylinders c where c.areckey = s.reckey limit 1
)
,""
) as isCyl
from schedule s
where s.assignmentDate between 20161015 and 20161016
order by s.reckey
Use a LEFT JOIN, which returns NULL for columns in the child table when there's no match.
SELECT s.reckey, IF(s.cylinders = "T",
IF(c.areckey IS NOT NULL, 'yes', 'no'),
"") AS isCyl
FROM schedule AS s
LEFT JOIN cylinders AS c ON c.areckey = s.reckey
WHERE s.assignmentDate between 20161015 and 20161016
ORDER BY s.reckey
If there can be multiple rows in cylinders with the same areckey, change it to:
LEFT JOIN (select distinct areckey FROM cylinders) AS c on c.areckey = s.reckey
or use SELECT DISTINCT in the main query.

Redirect row to another row mysql

id name redirect_id
1 .... NULL
2 ..... NULL
3 ..... 2
4 .... NULL
5 .... 1
i have this table. id is primary key. I want to get name of the row. However if it has a redirect_id, i want to get redirected id's name. Is there a possible way to do it in one sql query?
I know how to do it after fetching the result array. However it becomes so tangled if i do it that way. 1 sql query would be so good here. Thanks.
edit i need all redirected row not just redirrected name.
select ln.id
, COALESCE(ln2.name, ln.name)
from linkednames ln
left join linkednames ln2 on ln2.id = ln.redirect_id
If there is only one hop, then this is a simple join:
select t.id, (case when t.redirect_id is null then t.name else tr.name end) as name
from t left join
t tr
on t.redirect_id = tr.id;
If re-directs can have re-directs, you'll need more joins. MySQL does not have good support for hierarchical/recursive queries.

Complicated MySql Update Join Query

Have is an example of the problem I'm facing. The database tables are a little different than usual, but needed to be setup this way.
Items: id, order_id, other fields
Items_Drinks: id, drinks, other fields
Orders: id, other fields
Orders_Drinks: id, drinks, other fields
I need to have an update query that will update the Orders_Drinks table with the sum of the Items_Drinks drinks field that have the same order_id as Orders_Drinks id field.
Items: 1 1 ...
Items: 2 1 ...
Items_Drinks: 1 4 ...
Items_Drinks: 2 5 ...
Orders: 1 ...
Orders_Drinks: 1 9 ...
The Orders_Drinks is currently correct, but if I were to update Items_Drinks with id of 1 to 5, I would need an update command to get Orders_Drinks with id 1 to equal 10.
It would be best if the command would update every record of the Orders_Drinks.
I know my database is not typical, but it is needed for my application. This is because the Drinks table is not needed for all entries. The Drinks table has over 5000 fields in it, so if every record had these details the database would grow and slow for no real reason. Please do not tell me to restructure the database, this is needed.
I am currently using for loops in my C# program to do what I need, but having 1 command would save a ton of time!
Here is my best attempt, but it gives an error of "invalid group function".
update Orders_Drinks join Items on Items.order_id=Orders_Drinks.id join Items_Drinks on Items_Drinks.id=Items.id set Orders_Drinks.drinks=sum(Item_Drinks.drinks);
I think this is what you're wanting.
Edited:
UPDATE `Order_Drinks` a
SET a.`drinks` = (SELECT SUM(b.`drinks`) FROM `Items_Drinks` b INNER JOIN `Items` c ON (b.`id` = c.`id`) WHERE a.`id` = c.`order_id`)
That should give you a total of 9 for the Order_Drinks table for the row id of 1.
This is assuming that Orders.id == Orders_Drinks.id and that Items.id == Items_Drinks.id.
You need to do an aggregation. You can do this in the join part of the update statement:
update Orders_Drinks od join
(select i.order_id, sum(id.drinks) as sumdrinks
from Items i join
Items_Drinks id
on id.id = i.id
) iid
on iid.order_id = od.id
set od.drinks = iid.sumdrinks;
Something like this will return the id from the orders_drinks table, along with the current value of the drinks summary field, and a new summary value derived from the related items_drinks tables.
(Absent the name of the foreign key column, I've assumed the foreign key column names are of the pattern: "referenced_table_id" )
SELECT od.id
, od.drinks AS old_drinks
, IFNULL(td.tot_drinks,0) AS new_drinks
FROM orders_drinks od
LEFT
JOIN ( SELECT di.orders_drinks_id
, SUM(di.drinks) AS tot_drinks
FROM items_drinks di
GROUP BY di.orders_drinks_id
) td
ON td.orders_drinks_id = od.id
Once we have SELECT query written that gets the result we want, we can change it into an UPDATE statement. Just replace SELECT ... FROM with the UPDATE keyword, and add a SET clause, to assign/replace the value to the drinks column.
e.g.
UPDATE orders_drinks od
LEFT
JOIN ( SELECT di.orders_drinks_id
, SUM(di.drinks) AS tot_drinks
FROM items_drinks di
GROUP BY di.orders_drinks_id
) td
ON td.orders_drinks_id = od.id
SET od.drinks = IFNULL(td.tot_drinks,0)
(NOTE: the IFNULL function is optional. I just used it to substitute a value of zero whenever there are no matching rows in items_drinks found, or whenever the total is NULL.)
This will update all rows (that need to be updated) in the orders_drinks table. A WHERE clause could be added (after the SET clause), if you only wanted to update particular rows in orders_drinks, rather than all rows:
WHERE od.id = 1
Again, to get to this, first get a SELECT statement working to return the new value to be assigned to the column, along with the key of the table to be updated. Once that is working, convert it into an UPDATE statement, moving the expression that returns the new value down to a SET clause.

SQL Query Not Working - Not Picking Up Matching Rows

Ive been trying this query for half an hour - for some reason it only picks up the first row when I know that there are other rows that match the criteria. Any thoughts? Thanks.
SELECT `res`.id, `res`.time, `res`.price, `res`.ppl, `res`.rest, `city`.city
FROM `res`
JOIN `city` ON `res`.city = `city`.id
WHERE `res`.id > '0'
LIMIT 0 , 2
The data and the join don't match. There is only one city that will be returned with your query - joining res with city: city 6. and with that city there's only one res returned.

how to get other column when we use distinct in mysql query

When I use Distinct function in mysql query then I can get only one column from the table. This is example query that I am using:
SELECT DISTINCT (subcategory.title), common_cat. * FROM `subcategory`
LEFT JOIN common_cat ON ( subcategory.title = common_cat.ctitle )
It returns records as below :
title mid wid ctitle
Tops 17 5 Tops
Dresses NULL NULL NULL
Pants/Shorts 18 6 Pants/Shorts
Skirts NULL NULL NULL
Swimwear 24 8 Swimwear
Outerwear 21 9 Outerwear
In above data "Title" field coming from subcategory table.Now I also want to get id column
from subcategory table. How I can get this.
DISTINCT works by getting all the data of the columns you mentioned in a table row and then filtering out the duplicate rows and showing the unique rows with same values in ALL columns.
As such you can simply add the column subcategory.id to the column list and it will work.
SELECT DISTINCT subcategory.title, subcategory.id, common_cat.* FROM `subcategory`
JOIN common_cat ON ( subcategory.title = common_cat.ctitle )
Please note, in a distinct command it is not recommended to use * to pickup all columns as the more the number of columns in the query the more the load on the database server and hence a slower output. You may want to mention only the column names required in the distinct list and remove the common_cat.* from the query.