I want to order all rows of a table ("posts") by a (sort-)value ("sortDate") that is stored in a second table ("meta").
The (sort-)value of the second table is stored as a key-value pair. the key is 'publishDate'
The linking column between both tables is "postID".
The (sort-)value of the second table is optional, or can be entered multiple times.
-> If the (sort-)value is entered multiple times, i want to use the maximum.
-> If the (sort-)value is not present in the second table, i want to use the "postDate" - value of the first table instead.
This is my solution:
SELECT posts.postID,posts.postDate,metaDate.publishDate,
CASE
WHEN metaDate.publishDate is null Then posts.postDate
ELSE metaDate.publishDate
END AS sortDate /*fallback for those rows that do not have a matching key-value pair in second table*/
From posts
Left Join
(
Select meta.postID,MAX(metaValue) as publishDate
From meta
Where meta.metaKey = 'publishDate'
GROUP BY meta.postID
) As metaDate /*create a table with the maximum of publishDate, therefor handle multiple entries*/
ON posts.postID = metaDate.postID
ORDER BY sortDate DESC;
see also
sqlfiddle with this solution --->
Is there a smarte / faster way to do so?
As i am not a sql expert - anything i have overseen ?
(Background:
the structure of the tables is a wordpress-database-structure, therefore it is given, a related topic would be "sort posts by custom fields in wordpress" - but the solutions i found did not handle multiple or optional custom fields)
Thanks for comments and support
Related
It says that The database reported a syntax error:
Duplicate column name 'Product_Number'.
Below is the code:
SELECT *
FROM `df_all_orders_merged_la`
LEFT JOIN `product_database_la`
ON `df_all_orders_merged_la`.`Product_Number` = `product_database_la`.`Product_Number`
WHERE `product_database_la`.`Product_Number` IS NULL;
If both df_all_orders_merged_la and product_database_la contain a column named product_number you will get this error.
What you need to do is to disambiguate your request by using table aliases such as the letters p and m in this rewritten query:
SELECT m.*
FROM `df_all_orders_merged_la` m
LEFT JOIN `product_database_la` p
ON m.`Product_Number` = p.`Product_Number`
WHERE p.`Product_Number` IS NULL;
Here I have used the letters p and m to refer to particular tables in the FROM and JOIN section. Also notice what I did to the SELECT clause: I'm no longer pulling in anything from table p. (But I did this only to get rid of the immediate ambiguity ...)
In general, I recommend that you specify the fields that you actually need in your result, rather than relying on the SELECT * crutch in any of its many forms. Document, in the query, exactly what columns you really need, and which tables they come from:
SELECT m.order_id, p.product_number, p.product_name [...]
Actually you are joining the table and a new temporary table is formed on the basis of Product_Number column in the both parent table so in new table two duplicate column will be formed.
Now since you are calling select * from ... , due to * in select query mysql doesn't know which particular Product_Number column you want to select as having two same name column in this new table is ambigious to it without any specification(like Product_Name of which parent table you want to see) because astrick(*) replace * in query with all the column names in the specified table(without specifying any parent table and it becomes sometimes problematic in case of joins when there is/are column name having same name but different parent tables).
Think about if you are calling just by column name, how does mysql will know which parent table column it should show as there name can be same but there is possibility that content can be different or in just different order and it can't possibly know in this way which particular type column you want. maybe it shows you some random column among duplicates but you wanted some other column having same name!
so the way to select in this type of cases is by specifying the name of all the unique column just by column name(you can specify parent table too but it doesn't matter) without specifying parent table and for duplicate column you will have to call like
select `df_all_orders_merged_la`.`Product_Number,`product_database_la`.`Product_Number` from (... your join query here ...);
i.e specify the parent table of the column from which you want to show like above, again you can give alias to parent tables for your convenience
I have created a table with several columns and a related form. In that form, I have created a combobox to show the columns of the table in differents rows in combobox.
I have 3 fields in my table: product1, product2 and product3 for a same order I have named with a number. When I create the combobox, values show in 3 differents columns in the same row so I can just select the data from the first row and column. But what I need is the field's data displayed in different rows instead showing data in different columns.
I researched in forums, and I read It can be solved with a join query and selecting that in row source in combobox menu, but I have tried it and I got the same result. I donĀ“t know what am I doing wrong. I'd appreciate your help.
Thanks in advance.
You have to pivot the results
this is an example of how to restructure using sub queries bad data designs
SELECT *
FROM
(
SELECT QualifierID -- <--- this is a unique identifier
,
(
SELECT QualifierText
FROM [QDB].[dbo].[Qualifier] x
-- this is how you tie the unique identifier and grab a specific element by itself
-- also pay attention to how we're making it equal to q.QualifierID,
-- which is the alias to the table below
WHERE QualifierID=q.QualifierID
) AS QualifierText
,
(
SELECT [ExampleText]
FROM [QDB].[dbo].[Qualifier] x
-- this is how you tie the unique identifier and grab a specific element by itself
-- also pay attention to how we're making it equal to q.QualifierID,
-- which is the alias to the table below
WHERE QualifierID=q.QualifierID
) AS ExampleText
,
(
SELECT [WhenModified]
FROM [QDB].[dbo].[Qualifier] x
-- this is how you tie the unique identifier and grab a specific element by itself
-- also pay attention to how we're making it equal to q.QualifierID,
-- which is the alias to the table below
WHERE QualifierID=q.QualifierID
) AS WhenModified
FROM [QDB].[dbo].[Qualifier] q -- this is a table alias
) z -- this is the alias fo the subquery combining everything together.
I have a table that has Act ID, and another table that has Act ID, percentage complete. This can have multiple entries for different days. I need the sum of the percentage added for the Act ID on the first tableZA.108381.080
First table
Act ID Percent Date
ZA.108381.110 Total from 2 table
ZA.108381.120
ZA.108476.020
ZA.108381.110 25% 5/25/19
ZA.108381.110 75 6/1/19
ZA.108381.120
ZA.108476.020
This would be generally considering not good practice. Your primary key should be uniquely identifiable for that specific table, and any other data related to that key should be stored in separate columns.
However since an answer is not a place for a lecture, if you want to store multiple values in you Act ID column, I would suggest changing your primary key to something more generic "RowID". Then using vba to insert multiple values into this field.
However changing the primary key late in a databases life may cause alot of issues or be difficult. So good luck
Storing calculated values in a table has the disadvantage that these entries may become outdated as the other table is updated. It is preferable to query the tables on the fly to always get uptodate results
SELECT A.ActID, SUM(B.Percentage) AS SumPercent
FROM
table1 A
LEFT JOIN table2 B
ON A.ActID = B.ActID
GROUP BY A.ActID
ORDER BY A.ActID
This query allows you to add additional columns from the first table. If you only need the ActID from table 1, then you can simplify the query, and instead take it from table 2:
SELECT ActID, SUM(Percentage) AS SumPercent
FROM table2
GROUP BY ActID
ORDER BY ActID
If you have spaces other other special characters in a column or table name, you must escape it with []. E.g. [Act ID].
Do not change the IDs in the table. If you want to have the result displayed as the ID merged with the sum, change the query to
SELECT A.ActID & "." & Format(SUM(B.Percentage), "0.000") AS Result
FROM ...
See also: SQL GROUP BY Statement (w3schools)
I have a query i have been working on trying to get a specific set of data, join the comments in duplicate phone numbers of said data, then join separate tables based on a common field "entry_id" which also happens to be the number on the end of the word custom_ to pull up that table.
table named list and tables containing the values i want to join is custom_entry_id (with entry_id being a field in list in which i need the values of each record to replace the words in order to pull up that specific table) i need entry_id from the beginning part of my query to stick onto the end of the word custom for every value my search returns to get the fields from that custom table designated for that record. so it will have to do some sort of loop i guess? sorry like i said I am at a loss at this point
this is where i am so far:
SELECT * ,
group_concat(comments SEPARATOR '\r\n\r\n') AS comments_combined
FROM list WHERE `status` IN ("SALEA","SALE")
GROUP BY phone_number
//entry_id is included in the * as well as status
// group concat combines the comments if numbers are same
i have also experimented on test data with doing a full outer join which doesnt really exist. i feel if you can solve the other part for me i can do the joining of the data with a query similar to this.
SELECT * FROM test
LEFT JOIN custom_sally ON test.num = custom_sally.num
UNION
SELECT * FROM test
RIGHT JOIN custom_sally ON test.num = custom_sally.num
i would like all of this to appear with every field from my list table in addition to all the fields in the custom_'entry_id' tables for each specific record. I am ok with values being null for records that have different custom fields. so if record 1 has custom fields after the join of hats and trousers and record 2 has socks and shoes i realize that socks and shoes for record 1 will be null and hats and trousers for record 2 will be null.
i am doing all this in phpmyadmin under the SQL tab.
if that is a mistake please advise as well. i am using it because ive only been working with SQl for a few months. from what i read its the rookie tool.
i might be going about this all wrong if so please advise
an example
i query list with my query i get 20,000 rows with columns like status, phone_number, comments, entry_id, name, address, so on.
now i want to join this query with custom fields in another table.
the problem is the custom tables' names are all linked to the entry_id.
so if entry_id is 777 then the custom table fields are custom_777
my database has over 100 custom tables with specials fields for each record depending on its entry_id.
when i query the records I don't know how to join the custom fields that are entry_id specific to the rest of my data.i will pull up some tables and data for a better example
this is the list table:
this is the custom_"entry_id"
Full Outer Join in MySQL
for info on full outer joins.
I have 2 MySQL Tables: "parts_revisions" and "categories_revisions". My goal is to use the revisions data in these tables to create a log that lists out all the changes made to parts and categories. Listing the changes to "parts" in one single SQL statement has proven tricky though! Here is the situation:
All entries of each table have "timestamp" columns.
Every parts_revisions entry has a "categoryId" that basically links it to the categories_revisions table. (Every part is a child of a parent category.)
All I want to do is list out all the parts_revisions, but use the human-friendly "name" column from the categories_revisions table based on the categoryId column in parts_revisions. This will make the log more readable.
The trick is that, because there are usually multiple revisions for each category within the categories_revisions table, I cannot do just one big 'ol join on the categoryId column to get the name. The categoryId column is non-unique, and "name"s may vary. What I have to do is get the latest category_revisions entry that has a timestamp that is no later than the timestamp of the part_revisions entry. In other words, we want to get the appropriate category name that was in use AT THE TIME the part revision was made.
Not sure if this matches your table structure, but here's a go at it. It's a bit of an ugly subquery inside a subquery. Guessing it won't be terribly efficient
select part_name,
category,
(select name
from categories_revisions
where categories_revisions.match_id = parts_revisions.category
and categories_revisions.timestamp = (select MAX(categories_revisions.timestamp)
from categories_revisions
where categories_revisions.match_id = parts_revisions.category
and categories_revisions.timestamp < parts_revisions.timestamp)) as name
from parts_revisions;
http://sqlfiddle.com/#!2/da74e/1/0