MySQL join based on regexp - mysql

I have a table products where one of the columns are relatedproducts. relatedproducts contains strings of concatenated product IDs (column productid) separated by colon, e.g. abc-123:foo-prod:ada69, etc. Due to some bad design, there is the case that a product may be removed from products table and still be referenced in the relatedproducts column.
So I need a sql query that goes through all rows in products table, checks the relatedproducts column by exploding the data (hence the exploding the the title) and sees if each referenced product exists in the same products table. However, I am a novice at sql and having trouble writing the join/regexp query to do this.
Any help will be appreciated!

MySQL can match regexp's, but unfortunately cannot return the matched substring.
You better do it using FIND_IN_SET:
SELECT *
FROM products p
JOIN product rel
ON FIND_IN_SET(rel.id, REPLACE(p.related, ':', ','))

Related

The database reported a syntax error: Duplicate column name 'Product_Number'

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

mysql query using column values as parameter in query phpMyAdmin

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.

order table by optional value in second table (mysql, wordpress)

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

Combining table values in one output in SQL

I have two tables: one called tweets and one called references. tweets consists out of the rows tweet_id and classified amongst others. references consists out of the rows tweet_id and class_id.
The row tweet_id in the table references only consists out of a fraction of the total tweet_ids in the table tweets.
What I would like to do is combine these tables in such a way that the eventual table shows the rows r.tweet_id, t.classified and r.class_id.
I've come up with this query, but for some reason it shows zero rows of output. In reality however, there are about 900 rows in r.tweet_id which all exist in t.tweet_id.
SELECT 't.tweet_id', 't.classified', 'r.tweet_id', 'r.class_id'
FROM `tweets` t, `references` r
WHERE 'r.tweet_id' = 't.tweet_id'
Could somebody tell me what I am doing wrong and how I should change my script in order to get the desired outcome?
Mysql uses backticks ` to escape schema object names (columns, tables, databases) and apostrophes ' and quotes " to escape strings so you are comparing string r.tweet_id with string t.tweed_id in your condition (which is supposed to be false), do:
SELECT t.tweet_id, t.classified, r.tweet_id, r.class_id
FROM tweets AS t
INNER JOIN `references` AS r ON r.tweet_id = t.tweet_id
Note that you have to just escape word references because it's reserved word in mysql and you can omit other backticks.
Also if you also want to display rows like 1, 2, NULL, NULL (tweets that weren't classified) you can use LEFT JOIN instead of INNER JOIN;if you allow multiple classifications per one tweet, some GROUP BY (Aggregate) Functions may get handy.
BTW: PostgreSQL uses " for schema object names and ' for strings.

What's the mysql syntax to pull data on the fly

I have a table with a bunch of orders... one of the columns is order_status. The data in that column ranges from 1 to 5. Each number relates to a name, which is stored in another table that relates that number to the respective name.
SELECT order_id , order_status FROM tablename1
The above would just return the numbers 1,2,3,4,5 for order status. How can i query within the query on the fly to replace these numbers with their respective names.
Also, what's the term used to describe this. I'd Google it if i knew what the appropriate term was.
Each number relates to a name, which is stored in another table that
relates that number to the respective name.
JOIN it with the other table:
SELECT
t.order_id,
s.StatusName
FROM tablename1 AS t
INNER JOIN the statusesTable AS s ON t.order_status = s.status_id;