sql server: select either conditions using an OR clause? - asp.net

I have a Products tablet; in that there are a couple of fields like subcatid and designerid, which are coming from a Subcategories and Designers tables respectively. The website (ASP.NET C#) admin can insert some kind of Coupon Codes in a CouponCodes table by selecting either a designerid or a subcatid or both. This means that a particular product can be sold cheaper if either designerid or the subcatid fields or both for that product is found inside the CouponCodes table. Note, a Product does not necessarily have a designerid or a subcatid: An Admin can enter 'N/A' for either as Product is entered; the N/A has designerid of 27 and a subcatid of 9 in their respective tables. Probably not the best database design.
Anyway, here is my code in SSMS; when I try execute it I get an error of syntax. How to implement the sql? Thanks!
select * from couponcodes
where ( couponcodes.subcatid in
(select subcatid from Products where Products.prodid = 1012)
AND (couponcodes.couponcode = '5braceLets'))
OR
Where ( couponcodes.designerid in
(select designerid from Products where Products.prodid = 1012)
AND (couponcodes.couponcode = '5dora'))

You have where twice which is causing the syntax error. What you want to do is
select * from couponcodes
where ( couponcodes.subcatid in
(select subcatid from Products where Products.prodid = 1012)
AND (couponcodes.couponcode = '5braceLets'))
OR
( couponcodes.designerid in
(select designerid from Products where Products.prodid = 1012)
AND (couponcodes.couponcode = '5dora'))

Related

Sqlite SELECT with multiple conditions

I have to create a database with a PRODUCTS table and a CATEGORIES table.
Each product has a name, a price, a creation date and may belong to several categories.
Categories have a name and a flag to indicate whether the category is private or public.
Then I have to select all records that belongs to more than 5 public categories.
I've created the tables like this:
CREATE TABLE PRODUCTS (
ID_PROD int NOT NULL PRIMARY KEY,
NAME TEXT(255),
PRICE INTEGER,
CREATION_DATE DATE
);
CREATE TABLE CATEGORIES (
ID_CAT INTEGER NOT NULL PRIMARY KEY,
NAME TEXT(255),
PRIVATE INTEGER
);
CREATE TABLE PROD_CAT (
ID INTEGER NOT NULL PRIMARY KEY,
ID_PROD INTEGER,
ID_CAT INTEGER,
FOREIGN KEY (ID_PROD) REFERENCES PRODUCTS(ID_PROD),
FOREIGN KEY (ID_CAT) REFERENCES CATEGORIES(ID_CAT)
)
I've managed to select all the records that belongs to more than 5 categories but I can't find out how to add the public category condition...
Here's what I've tried:
This works:
SELECT NAME
FROM PRODUCTS
WHERE ID_PROD IN (SELECT ID_PROD FROM PROD_CAT GROUP BY ID_PROD HAVING COUNT(*)>5)
But not this:
SELECT PRODUCTS.NAME
FROM PRODUCTS, CATEGORIES
WHERE ID_PROD IN (SELECT ID_PROD FROM PROD_CAT GROUP BY ID_PROD HAVING COUNT(*)>5)
AND CATEGORIES.PRIVATE = 1
Any help would be appreciated :)
You need a join of PROD_CAT to CATEGORIES:
SELECT NAME
FROM PRODUCTS
WHERE ID_PROD IN (
SELECT pc.ID_PROD
FROM PROD_CAT pc INNER JOIN CATEGORIES c
ON c.ID_CAT = pc.ID_CAT
WHERE c.PRIVATE -- or WHERE NOT c.PRIVATE for public categories
GROUP BY pc.ID_PROD
HAVING COUNT(*) > 5
)
Or, without the operator IN, with joins of all 3 tables:
SELECT p.ID_PROD, p.NAME
FROM PRODUCTS p
INNER JOIN PROD_CAT pc ON pc.ID_PROD = p.ID_PROD
INNER JOIN CATEGORIES c ON c.ID_CAT = pc.ID_CAT
WHERE c.PRIVATE -- or WHERE NOT c.PRIVATE for public categories
GROUP BY p.ID_PROD, p.NAME
HAVING COUNT(*) > 5
Since this looks like homework, I'll give a good hint.
Your first query returns products belonging to more than 5 categories, using a sub-query for the COUNT. The restriction you added in the second query was added to the top-level WHERE-clause, not the sub-query. The sub-query still works on PROD_CAT and still returns the same results, which may include public categories.

Retrieve Record Based on a Value Existing in Record's Association Table

I have two tables. posts is the record I want, whilst post_tags allows a one-to-many relationship between them. NB. I have this working, however, they do not feel efficient to me and I could do with some SQLite gurus to help me out.
posts
id
post_tags
post_id
tag
Exact Match
I want to be able to retrieve posts that match a specific tag that I pass in.
Here is my current query.
SELECT * FROM posts WHERE "desiredTag" IN (SELECT tag FROM post_tags WHERE post_id = posts.id AND tag = "desiredTag");
One Of
My next requirement is an adaptation of the first. Instead of just matching one tag, I want to be able to pass in an array of tags and posts to be returned when they match at least one of the passed in tags. Again, I have this working but inefficiently.
SELECT * FROM posts WHERE ("tagOne" IN (SELECT tag FROM post_tags WHERE post_id = posts.id AND tag = "tagOne") OR "tagTwo" IN (SELECT tag FROM post_tags WHERE post_id = posts.id AND tag = "tagTwo"));
Usually EXISTS performs better:
SELECT p.*
FROM posts p
WHERE EXISTS (SELECT 1 FROM tag t WHERE t.post_id = p.id AND t.tag IN ('tag1', 'tag2'))
Or you could do it with an INNER JOIN:
SELECT DISTINCT p.*
FROM posts p INNER JOIN tag t
ON t.post_id = p.id
WHERE t.tag IN ('tag1', 'tag2')

Selecting all max values of column for each distinct value of other column

I am trying to get a list of most used tags for posts on a website on a given day. I currently have this query:
SELECT posts.pdate, tags.tag, count(posts.pid) as post_count
FROM posts, tags
WHERE posts.pid = tags.pid
GROUP BY posts.pdate, tags.tag
ORDER BY posts.pdate;
This provides me with each distinct tag, along with the date they are used on as well as how many posts used them, returning me with this:
2020-09-10|CMPUT291|1
2020-09-10|computing|1
2020-09-10|database|2
2020-09-10|frequentTag1|2
2020-09-10|relational|2
2020-09-10|sql|1
2020-09-10|tieTag1|2
2020-09-11|Database|1
2020-09-11|data|1
2020-09-11|relational|1
2020-09-11|sql|1
2020-09-13|Database|1
2020-09-13|Sql language|1
2020-09-13|access|1
2020-09-13|frequentTag3|2
2020-09-13|query|3
2020-09-13|relational|3
2020-09-13|sql|1
2020-09-17|Database|1
2020-09-17|frequentTag3|3
2020-09-17|query|1
2020-09-17|relational|1
2020-09-17|sql|1
2020-09-17|sql language|1
2020-09-20|RELATIONAL|1
2020-09-20|database|1
2020-09-20|query|1
2020-09-20|sql language|1
2020-09-25|database|1
2020-09-25|sql language|1
2020-09-30|boring|2
2020-09-30|extra tag|1
2020-09-30|fun|3
2020-09-30|just here|1
2020-09-30|more tag|1
2020-09-30|sleep|3
2020-09-30|tag tag|1
2020-09-30|tag test|1
2020-09-30|test tag|1
But, I now need to make it only give me the rows that have the max (or all of them with max in case of a tie) for each date.
I WANT to be able to use MAX(count(posts.pid)) but I know that doesn't work so I need to find an alternative.
I should get a final result of this:
2020-09-10|database|2
2020-09-10|frequentTag1|2
2020-09-10|relational|2
2020-09-10|tieTag1|2
2020-09-11|Database|1
2020-09-11|data|1
2020-09-11|relational|1
2020-09-11|sql|1
2020-09-13|query|3
2020-09-13|relational|3
2020-09-17|frequentTag3|3
2020-09-20|RELATIONAL|1
2020-09-20|database|1
2020-09-20|query|1
2020-09-20|sql language|1
2020-09-25|database|1
2020-09-25|sql language|1
2020-09-30|fun|3
2020-09-30|sleep|3
Any help would be greatly appreciated.
APPLICABLE SCHEMA:
create table posts (
pid char(4),
pdate date,
title text,
body text,
poster char(4),
primary key (pid),
foreign key (poster) references users
);
create table tags (
pid char(4),
tag text,
primary key (pid,tag),
foreign key (pid) references posts
);
You can use RANK() window function:
SELECT pdate, tag, post_count
FROM (
SELECT p.pdate,
t.tag,
COUNT(*) post_count,
RANK() OVER (PARTITION BY p.pdate ORDER BY COUNT(*) DESC) rnk
FROM posts p INNER JOIN tags t
ON p.pid = t.pid
GROUP BY p.pdate, t.tag
)
WHERE rnk = 1
ORDER BY pdate, tag;
You should use a proper JOIN with an ON clause instead of that outdated syntax with the WHERE clause.

Import drupal database table data to wordpress database

i have my current working site on wordpress. i want to import data from database which had in another server working on drupal. How can i import all the data from table in drupal site to my current working website database in wordpress. Please help me with this
First Option : Steps and applicable queries to migrate your Drupal database to WordPress:
1. Make a backup of both your Drupal and WordPress databases.
2. Before converting Drupal to WordPress, make sure that in your original Drupal install the taxonomies are correctly labeled. Step 11 will further discuss fixing taxonomy.
3. Create a new WordPress installation in a different database
from your Drupal installation. Name the different databases
‘drupal’ and ‘wordpress’.
4. Clear out previous content from the WordPress database by
running this command in your database’s SQL queries tab in
phpmyadmin.
TRUNCATE TABLE wordpress.wp_comments;
TRUNCATE TABLE wordpress.wp_links;
TRUNCATE TABLE wordpress.wp_postmeta;
TRUNCATE TABLE wordpress.wp_posts;
TRUNCATE TABLE wordpress.wp_term_relationships;
TRUNCATE TABLE wordpress.wp_term_taxonomy;
TRUNCATE TABLE wordpress.wp_terms;
5. Apply this code to convert over multiple users.
DELETE FROM wordpress.wp_users WHERE ID > 1;
DELETE FROM wordpress.wp_usermeta WHERE user_id > 1;
6. To migrate over tags, use the following code...
(To ensure duplicate names don’t get lost, make sure that the
Drupal term_data table has been cleaned of all duplicate names.)
REPLACE INTO wordpress.wp_terms
(term_id, `name`, slug, term_group)
SELECT DISTINCT
d.tid,
d.name,
REPLACE(LOWER(d.name), ' ', '_'), 0
FROM drupal.term_data d
INNER JOIN drupal.term_hierarchy h
USING(tid)
WHERE (1
)
;
INSERT INTO wordpress.wp_term_taxonomy
(term_id, taxonomy, description, parent)
SELECT DISTINCT
d.tid `term_id`,
'post_tag' `taxonomy`,
d.description `description`,
h.parent `parent`
FROM drupal.term_data d
INNER JOIN drupal.term_hierarchy h
USING(tid)
INNER JOIN drupal.term_node n
USING(tid)
WHERE (1
)
;
7. To convert over posts, apply the following query:
INSERT INTO wordpress.wp_posts
(id, post_author, post_date, post_content, post_title,
post_excerpt, post_name, post_modified, post_type,
`post_status`)
SELECT DISTINCT
n.nid `id`,
n.uid `post_author`,
FROM_UNIXTIME(n.created) `post_date`,
r.body `post_content`,
n.title `post_title`,
r.teaser `post_excerpt`,
IF(SUBSTR(a.dst, 11, 1) = '/', SUBSTR(a.dst, 12),
a.dst) `post_name`,
FROM_UNIXTIME(n.changed) `post_modified`,
n.type `post_type`,
IF(n.status = 1, 'publish', 'private') `post_status` FROM
drupal.node n
INNER JOIN drupal.node_revisions r
USING(vid)
LEFT OUTER JOIN drupal.url_alias a
ON a.src = CONCAT('node/', n.nid)
# If applicable, add more Drupal content types below.
WHERE n.type IN ('post', 'page', 'blog')
;
*If your Drupal installation has multiple post types, be sure to
add the name of the post type into this line: WHERE n.type IN
(‘post’, ‘page’, ‘blog’). Failure to do so will result in not all posts
types being converted over.
8. To combine post types in WordPress, run this script:
UPDATE wordpress.wp_posts
SET post_type = 'post' WHERE
post_type IN ('blog') ;
9. To define the post/tag relationship, apply the following:
INSERT INTO wordpress.wp_term_relationships (object_
id, term_taxonomy_id)
SELECT DISTINCT nid, tid FROM drupal.term_node
;
# Update tag counts.
UPDATE wp_term_taxonomy tt
SET `count` = (
SELECT COUNT(tr.object_id)
FROM wp_term_relationships tr
WHERE tr.term_taxonomy_id = tt.term_taxonomy_id
)
;
10.Apply this query to migrate comments:
INSERT INTO wordpress.wp_comments
(comment_post_ID, comment_date, comment_content,
comment_parent, comment_author,
comment_author_email, comment_author_url, comment_
approved)
SELECT DISTINCT
nid, FROM_UNIXTIME(timestamp), comment, thread, name,
mail, homepage, ((status + 1) % 2)
FROM drupal.comments
;
# Update comments count on wp_posts table.
UPDATE wordpress.wp_posts
SET `comment_count` = (
SELECT COUNT(`comment_post_id`)
FROM wordpress.wp_comments
WHERE wordpress.wp_posts.`id` = wordpress.wp_
comments.`comment_post_id`
)
;
11.You do not have to do anything if you want to keep your
Drupal images and files in the same location, but if you are
FTP-ing your files to the uploads folder in your WordPress
wp-content folder, use the following code to fix the image
URLs.
UPDATE wordpress.wp_posts SET post_content =
REPLACE(post_content, ‚“/files/‘, ‚“/wp-content/
uploads/‘);
12.To fix taxonomy (assuming you’ve set it up correctly in your
original Drupal site), use the following code:
UPDATE IGNORE wordpress.wp_term_relationships,
wordpress.wp_term_taxonomy
SET wordpress.wp_term_relationships.term_taxonomy_id =
wordpress.wp_term_taxonomy.term_taxonomy_id
WHERE wordpress.wp_term_relationships.term_taxonomy_id
= wordpress.wp_term_taxonomy.term_id
;
13.To assign author roles for your users, here’s the code:
INSERT IGNORE INTO wordpress.wp_users
(ID, user_login, user_pass, user_nickname, user_email,
user_registered, user_activation_key, user_status,
display_name)
SELECT DISTINCT
u.uid, u.mail, NULL, u.name, u.mail,
FROM_UNIXTIME(created), ‚' ', 0, u.name
FROM drupal.users u
INNER JOIN drupal.users_roles r
USING (uid)
WHERE (1
# Uncomment and enter any email addresses you want to
exclude below.
# AND u.mail NOT IN (‚test#example.com‘)
)
;
14.Here’s the code you can use to set the author role’s permissions:
INSERT IGNORE INTO wordpress.wp_usermeta (user_id,
meta_key, meta_value)
SELECT DISTINCT
u.uid, 'wp_capabilities',
'a:1:{s:6:“author“;s:1:“1“;}'
FROM drupal.users u
INNER JOIN drupal.users_roles r
USING (uid)
WHERE (1
# Uncomment and enter any email addresses you want to
exclude below.
# AND u.mail NOT IN ('test#example.com')
)
;
INSERT IGNORE INTO wordpress.wp_usermeta (user_id,
meta_key, meta_value)
SELECT DISTINCT
u.uid, 'wp_user_level', '2'
FROM drupal.users u
INNER JOIN drupal.users_roles r
USING (uid)
WHERE (1
# Remove and enter any email addresses you want to
exclude below.
# AND u.mail NOT IN ('test#example.com')
)
;
You can remove the number sign before the line that has
the email address and put your own in so that your remain
the administrator.
15.Use this code to assign and give administrator status:
UPDATE wordpress.wp_usermeta
SET meta_value = 'a:1:{s:13:“administrator“;s:1:“1“;}‘
WHERE user_id IN (1) AND meta_key = 'wp_capabilities' ;
UPDATE wordpress.wp_usermeta
SET meta_value = '10'
WHERE user_id IN (1) AND meta_key = 'wp_user_level'
;
16.This code will help assign authors to the posts they wrote:
UPDATE wordpress.wp_posts
SET post_author = NULL
WHERE post_author NOT IN (SELECT DISTINCT ID FROM
wordpress.wp_users)
;
17. You can then feed the following code for the editor to help
clean it up so that your posts don’t look bizarre after the
conversion.
UPDATE wordpress.wp_posts
SET post_name =
REVERSE(SUBSTRING(REVERSE(post_
name),1,LOCATE('/',REVERSE(post_name))-1)) ;
That’s the basics of migrating your Drupal site to WordPress.
Second Option : Using with Plugin To Migrate you Drupal Database to Wordpress
In this section, we’ll be using the FG Drupal to WordPress plugin to carry out our migration. This tool is remarkably simple to use, and we’ll cover how to use it in this piece. However, if you do happen to run into any errors, the plugin’s documentation should see you through.
It’s worth noting this plugin also comes in a premium version, but the free option is more than enough to carry out a regular migration. However, if you’re looking to move multiple authors, your comments, users, and even custom post types, the premium version might be worth considering.
Step #1: Install and activate the FG Drupal to WordPress plugin
Step #2: Find out your Drupal database parameters
Step #3: Import your Drupal content into WordPress
Get more details, you can follow the link - How to migrate Drupal to WordPress (in 3 steps)

TYPO3 Extbase order by child records COUNT

I have this model:
News -> 1:n -> Visit
News -> m:n -> FrontendUserGroup
FrontendUser -> 1:n -> Visit
So Visit shows which FrontendUser accessed which News.
I need to get all news for the currently logged in FrontendUser.
All News should be ordered DESC by the "datetime" property, but first should appear the news which are not visited yet by the logged in user.
This is the SQL which gives me the correct results:
SELECT
(SELECT COUNT(*) FROM tx_xxnews_domain_model_visit v WHERE v.news = n.uid AND v.fe_user = fu.uid) AS visits,
n.*
FROM tx_xxnews_domain_model_news AS n
JOIN tx_xxnews_news_frontendusergroup_mm nfg ON n.uid = nfg.uid_local
JOIN fe_users fu ON FIND_IN_SET(nfg.uid_foreign, fu.usergroup)
WHERE fu.uid = 2271 # logged in user id
ORDER BY visits ASC, n.datetime DESC
Is there any way to get this result with Extbase?
I tried in NewsRepository this:
protected $defaultOrderings = array(
'COUNT(visits)' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING,
'datetime' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING
);
but it doesn't seem to work.
Any ideas?
Thank you.
This is in fact not possible since $defaultOrderings expects properties, not SQL field names or functions.
As far as I know, the only possibility is to use$query->statement('[YOUR QUERY]');.

Resources